我试图一次读入用户输入的一个词,直到用户打印输入。目前这在读取时有效,直到按下回车键,但一次只读取一个字符。关于如何改为逐字阅读有什么建议吗?
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char a[256];
int i=0;
do{
cin>>a[i++];
} while(cin.peek() != '\n');
for(int j= 0 ; j < i ; j++)
cout<< a[j] << " ";
return 0;
}
最佳答案
你可以尝试使用
std::string a[256];
代替
char a[256];
但是,使用的逻辑
while(cin.peek() != '\n');
有缺陷。如果您在按下 Enter 之前输入空格字符,您的程序将等待您输入更多内容。
使用std::getline()
会更好读取一行文本,然后使用 stringstream
解析该行文本.
我还建议使用 std::vector<std::string>
而不是 std::string
的数组.
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
int main()
{
std::vector<std::string> words;
std::string line;
getline(std::cin, line);
std::istringstream str(line);
std::string word;
while ( str >> word )
{
words.push_back(word);
}
for ( auto& w : words )
{
std::cout << w << " ";
}
return 0;
}
关于C++ - 一次读入一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32898558/