1

I'm writing an small program in C++ and have an input file and need to read line by line, there're 2 columns in file, string name and integer number. for example:

abad 34
alex 44
chris 12

I wrote such code:

ifstream input("file.txt");
int num;
string str;

while( getline( input, line ) ){
  istringstream sline( line );
  if( !(sline>>str>>num) ){
     //throw error
  }
  ...
}

I need to throw errors in cases:

if there's no number - only name is written e.g. abad (actually I'm getting error with my code),

if there's a name and no number, e.g.: abad 34a(letter a in 34a is ignored and transferred to just 34 in my code while error should be triggered),

or if there're more than 2 columns e.g. abad 34 45 (2nd number is ignored).

How to read correctly input data ( and without iterators )?

4

2 回答 2

2

尝试这个:

if( !(sline >> str >> num >> std::ws) || sline.peek() != EOF ) {
     //throw error
}

std::ws是一个流操纵器,用于提取后面可能出现的空白num。包括<iomanip>它。接下来检查在流中窥视是否返回 EOF。如果没有,你有更多的输入等待,这是一个错误。

于 2013-03-24T11:17:01.873 回答
1

请尝试以下操作: 保留std::vector每行中读取的所有字符串,以便您能够更轻松地处理它们。那么,分三种情况:

  • 没有数字:vec.size( ) = 1。
  • 超过两个字符串:vec.size( ) > 2。
  • 无效数字:不是所有 vec[1] 的数字都是数字

代码:

#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <cstdlib>
#include <cctype>

using namespace std;

int main( ) {
  fstream in( "input.txt", fstream::in );
  fstream out( "error.txt", fstream::out );

  string line;

  while( getline( in, line ) ) {
    vector< string > cmd;
    istringstream istr( line );
    string tmp;

    while( istr >> tmp ) {
      cmd.push_back( tmp );
    }

    if( cmd.size( ) == 1 ) // Case 1: the user has entered only the name
    {
      out << "Error: you should also enter a number after the name." << endl; // or whatever
      continue; // Because there is no number in the input, there is no need to proceed
    }
    else if( cmd.size( ) > 2 ) // Case 3: more than two numbers or names
    {
      out << "Error: you should enter only one name and one number." << endl;
    }

    // Case 2: the user has enetered a number like 32a

    string num = cmd[ 1 ];

    for( int i = 0; i < num.size( ); ++i ) {
      if( !isdigit( num[ i ] ) ) {
        out << "Error: the number should only consist of the characters from 1-9." << endl;
        break;
      }
    }
  }

  return 0;
}

文件:输入.txt

abad 34
alex 44
chris 12
abad
abad 24a
abad 24 25

文件:error.txt

Error: you should also enter a number after the name.
Error: the number should only consist of the characters from 1-9.
Error: you should enter only one name and one number.
于 2013-03-24T11:29:45.647 回答