我的代码中有char的问题,请指导我(c ++).
我有这个错误:Run-Time Check Failure #3 - The variable 'op' is being used without being initialized.它是什么意思,我该如何解决?
这是我的代码:
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
using namespace std;
enum Operations {SIN1, COS1, TAN1};
void selectenteroperation(char *szInput) {
char *szLabels[3] = {"sin", "cos", "tan"};
int i=0;
while(strcmp(szInput,szLabels[i])==0)
++i;
switch (i)
{
case SIN1: { cout<<"SIN"; break; }
case COS1: { cout<<"COS"; break; }
case TAN1: { cout<<"TAN"; break; }
default: { cout<<"Wrong"; break; }
}
}
void main() {
char *op;
cout<<"op?";
cin>>op;
if(strcmp(op,"sin")==0) selectenteroperation("sin");
if(strcmp(op,"cos")==0) selectenteroperation("cos");
if(strcmp(op,"tan")==0) selectenteroperation("tan");
}
Run Code Online (Sandbox Code Playgroud)
这是因为char *op只创建一个字符指针,而不是用于保存字符串的后备存储.
由于这是C++,你应该使用std::string.旧式C字符串有其用途,但易于使用的字符串不是其中之一.
拥抱C++,有足够多的C程序员试图像C++大师一样将自己传递出去:-)
因为这看起来像功课,我不会给你回你完全固定的计划,但我会为您提供一个可以被用作测试的基础,更重要的是,了解:
pax$ cat qq.cpp ; g++ -o qq qq.cpp
#include <iostream>
int main (void) {
std::string s;
std::cout << "Enter something: ";
std::cin >> s; // or getline (std::cin, s).
std::cout << "You entered [" << s << "]" << std::endl;
return 0;
}
pax$ ./qq
Enter something: hello
You entered [hello]
Run Code Online (Sandbox Code Playgroud)
或者,如果你真的想使用C字符串,例如:
#include <iostream>
int main (void) {
char s[256];
std::cout << "Enter something: ";
std::cin.getline (s, sizeof (s));
std::cout << "You entered [" << s << "]" << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
可能是合适的.
| 归档时间: |
|
| 查看次数: |
321 次 |
| 最近记录: |