如何在C ++中检查字符串数组是否有换行符?

时间:2016-04-15 05:20:03

标签: c++ string

  #include<sstream>
  #include<iostream>
  using namespace std;

  int main(){
     string line = "test one two three. \n another one \n";
     string arr[8];
     cout<<line;
     int i = 0;
     stringstream ssin(line);
     while (ssin.good() && i < 8){
         ssin >> arr[i];
         ++i;
     }
     for(i = 0; i < 8; i++){
        cout << arr[i];
     } 
  return 0; 
  }

//现在我想打印字符串中换行符(“\ n”)之前的元素。

3 个答案:

答案 0 :(得分:0)

您的ssin >> arr[i]跳过空白,丢失所有arr条目后跟换行符的知识。

相反,您可以先将输入划分为行,然后将字符划分为单词,同时跟踪换行符:

std::vector<size_t> newline_after_word_index;
std::vector<std::string> words;
while (getline(ssin, line))
{
    std::istringstream line_ss(line);
    std::string word;
    while (line_ss >> word)
        words.push_back(word);
    newline_after_word_index.push_back(words.size());
}

然后,您可以使用newline_after_word_index中的索引预先打印words[]条目....

答案 1 :(得分:0)

不要将"test one two three. \n another one \n"视为一行文字。它不是。这是两行文字。

你需要改变你的阅读策略。

int main()
{
   string input = "test one two three. \n another one \n";
   string arr[8];
   int i = 0;

   stringstream ssin_1(input);
   string line;

   // Read only the tokens from the first line.
   if ( std::getline(ssin_1, line) )
   {
      stringstream ssin_2(line);
      while ( ssin_2 >> arr[i] && i < 8)
      {
         ++i;
      }
   }

   // Don't print all the elements of arr
   // Print only what has been read.
   for(int j = 0; j < i; j++){
      cout << arr[j] << " ";
   } 

   return 0; 
}

答案 2 :(得分:0)

http://www.cplusplus.com/reference/string/string/find/

#include<sstream>
#include<iostream>
using namespace std;
int main(){
    string line = "test one two three. \n another one \n";
    size_t found = line.find("\n");
    for (int i=0; i<=found; i++){
      cout << line[i];
    }
return 0; }