如何在C ++中识别新行?

时间:2009-10-17 06:01:25

标签: c++

我必须将整数输入转换为整数数组。我必须在输入中识别换行符。 为了更清楚,我有一个例子。 我给的输入是: -

2
3
4

45
6
78
45

34
34

我想根据输入中的换行符处理输入。

编程语言是C ++,编译器是g ++。我不想将换行存储在数组中;我只想相应地处理。

4 个答案:

答案 0 :(得分:7)

您可以使用< string>中的std :: getline读取整行并使用std :: stringstream,来自< sstream>解析线条。

答案 1 :(得分:0)

虽然你提到c ++,但我常常用它来读取文件中的双打数组

 char line[512+1];

  unsigned int row = 0 ;
  unsigned int col = 0 ;

  while( fgets(line, sizeof(line), file) )
    {
      col = 0 ;
      tempChr = strtok(line, delimters);

      // ignore blank lines and new lines
      if ( tempChr[0] == '\n' )
    {
      continue ;
    }

      tempDbl = atof(tempChr);

      data[row*numCols+col] = tempDbl ;


      for(col = 1 ; col < numCols ; ++col)
    {
      tempDbl = atof(strtok(NULL, delimters));
      data[row*numCols+col] = tempDbl;
    }

      row = row + 1;
      if( row == numRows )
    {
      break ;
    }
    }

答案 2 :(得分:0)

int array[42];
int* ptr = array;
for (string line; getline(cin, line); ) {
    istringstream stream(line);
    stream >> *ptr++;
}

错误检查已被删除。

答案 3 :(得分:0)

istream提取操作符将自动跳过输入中的空白行,因此下面示例中的read_ints()函数将返回输入流中空格(包括换行符)分隔值的向量。

#include <vector>
#include <iostream>

using namespace std;

vector<int>
read_ints(istream & is)
{
    vector<int> results;
    int value;
    while ( is >> value )
    {
        results.push_back(value);
    }
    return results;
}

int
main(int argc, char * argv[])
{
    vector<int> results = read_ints(cin);
    for ( vector<int>::const_iterator it = results.begin(); it != results.end(); ++it )
        cout << *it << endl;

    return 0;
}

如果任何输入无法解析为int并且允许整数由空格和换行符分隔,则上述代码将停止读取,因此可能与问题的要求不完全匹配。