【问题标题】:C++ - Read in input one word at a timeC ++ - 一次读入输入一个单词
【发布时间】:2015-10-01 23:54:11
【问题描述】:

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

#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::getlinestd::string 组合起来并标记字符串。比处理缓冲区溢出要好得多。
  • 可能想改写问题。 cin 在用户点击回车之前不会给你任何输入。

标签: c++ cin


【解决方案1】:

你可以试试

std::string a[256];

而不是

char a[256];

但是,使用的逻辑

while(cin.peek() != '\n');

有缺陷。如果您在按 Enter 之前输入空格字符,您的程序将等待您输入更多输入。

最好使用std::getline()读取一行文本,然后使用stringstream解析该行文本。

我还将建议使用std::vector&lt;std::string&gt; 而不是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;
}

【讨论】:

    【解决方案2】:

    这是使用getlinestd::strings 的容器的另一种紧凑方式

    #include <iostream>
    #include <iterator>
    #include <algorithm>
    #include <string>
    
    int main() 
    {
        std::vector<std::string> tokens;
        std::copy(std::istream_iterator<std::string> {std::cin}, {}, 
                  std::back_inserter(tokens));
        for(auto && elem: tokens)
            std::cout << elem << '\n';
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-12
      • 2013-01-11
      • 2014-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      相关资源
      最近更新 更多