一个字符串数组, 输入到回车停止输入. 输出这个数组里输入元素的个数.

我的思想是这样的.#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char a[20];
for(int i=0; i < 10; i ++)
{
cin >> a[i];
if(a[i] == '\n')
break;
}
cout << strlen(a);
}为什么运行不出正确结果?

cin回跳过空格和换行,所以a[i]永远不会接收到'\n',for循环循环10次,当输入的字符少于10个,for循环就还没执行完,所以不会输出结果。其实何必用这么麻烦的方法接收字符串,直接用cin.getline(a,20);就可以了:#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char a[20];
cin.getline(a,20);cout << strlen(a);
}
温馨提示:答案为网友推荐,仅供参考