在小弟我输入一串字符的时候,如何用cin>>x当打回车的时候结束
在我输入一串字符的时候,怎么用cinx当打回车的时候结束C/C++ code/*作业一、计算输入的句子内所含的字符
在我输入一串字符的时候,怎么用cin>>x当打回车的时候结束
C/C++ code/*作业一、计算输入的句子内所含的字符数。 1,整数变量,计算字符数 2,处理输入句子的函数 3,显示字符数的函数*/#include<iostream>using namespace std;int main(){ int num; //1,整数变量,计算字符数 int input(void); //2,处理输入句子的函数 num=input(); void output(int num); //3,显示字符数的函数 output(num); return 0;};int input(void){ cout <<"input the datas:" <<'\n'; char x; int num=0; while((cin>>x)!='\n') { ++num; } return num;};void output(int num){ cout <<"There are " <<num <<" chars in the string." <<"\n";};
疑问:1.在我输入一串字符的时候,怎么用cin>>x当打回车的时候结束。
2.提示下还有别的方法可以实现吗,除了用数组的那个方法。
错误提示:error C2679: binary '!=' : no operator defined which takes a right-hand operand of type 'const char' (or there is no acceptable conversion)
谢谢各位了。
[解决办法](cin>>x)!='\n')
这个operator >>返回值不是char类型,应该是ostream&,所以不能与'\n'相比较,应该用x与'\n'比较
[解决办法]因为x是char型 用cin显然不合适 用getchar()显然更合适
[解决办法]这里,整个语句是一个整体: while((cin>>x)!='\n')
而其中的(cin>>x)又是一个整体,(cin>>x)的返回值不是楼主想当然的x,当然也就不等于'\n'了。
用getch()吧。
以下来自MSDN:
cin
extern istream cin;
The object controls extractions from the standard input as a byte stream. Once the object is constructed, the call cin.tie() returns &cout.