C++ - 一次读入一个单词

标签 c++ cin

我试图一次读入用户输入的一个词,直到用户打印输入。目前这在读取时有效,直到按下回车键,但一次只读取一个字符。关于如何改为逐字阅读有什么建议吗?

#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/

相关文章:

c++ - 混合cin >>和getline()-C++

C++ 不要进入我的cin

c++ - C++ 中对不存在的对象进行赋值

c++ - 通过 void* 转换到基地

c++ - 使用多色 GDI C++ 绘制线条

c++ - snprintf Format String 安全漏洞问题

c++ - 为什么看起来我的对象被销毁了两次?

c++ - cin 缓冲区没有被忽略?

c++ - cin std::string 带空格

c++ - 如果 cin 在字符串之前包含整数,则打印错误