读字符串直到行尾?

时间:2014-11-05 23:35:29

标签: c++

有没有办法读取由空格分隔的连续单词作为字符串,直到在C ++中找到行尾?确切地说,我正在研究算法问题,输入如下:

some_word1 some_word2 some_word3 (...) some_wordn
other_data

诀窍是我不知道第一行会有多少单词,只是我应该将它们作为单独的单词进行进一步处理。我知道我可以使用getline(),但之后我必须使用char-by-char在空格出现时将每个单词写入一个新字符串。这不是很多工作,我只是好奇是否有更好的方法。

3 个答案:

答案 0 :(得分:4)

使用getline后,为什么要逐个字符地工作? 解析面向行的输入的常用方法是逐行读取, 使用getline,然后使用std::istringstream来解析该行 (假设这是最合适的解析工具,就像在你的 案件)。所以要阅读文件:

std::string line;
while ( std::getline( input, line ) ) {
    std::istringstream parse( line );
    //  ...
}

答案 1 :(得分:2)

您可以使用sstream并将其与getline()结合使用,这是您已经知道的事情。

#include <iostream>
#include <sstream>

int main()
{
    std::string fl;
    std::getline(std::cin, fl); // get first line

    std::istringstream iss(fl);
    std::string word;
    while(iss >> word) {
        std::cout << "|" << word << "|\n";
    }

    // now parse the other lines
    while (std::getline(std::cin, fl)) {
      std::cout << fl << "\n";
    }
}

输出:

a b
|a|
|b|
a
a
g
g
t
t

您可以看到未保存空格。


在这里您可以看到相关答案:

  1. Split a string in C++
  2. Taking input of a string word by word

答案 2 :(得分:0)

我建议将整行读作字符串并将字符串拆分为字符串向量。 可以从此问题Split a string in C++?

中找到拆分字符串
string linestr;
cin>>linestr;
string buf; // Have a buffer string
stringstream ss(linestr); // Insert the string into a stream

vector<string> tokens; // Create vector to hold our words

while (ss >> buf)
    tokens.push_back(buf);
相关问题