1

私はC++で小さなプログラムを書いていて、入力ファイルがあり、行ごとに読む必要があります.ファイルには2つの列、文字列名と整数番号があります. 例えば:

abad 34
alex 44
chris 12

私はそのようなコードを書きました:

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

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

次の場合にエラーをスローする必要があります。

番号がない場合 - 名前のみが書き込まれabadます (実際、コードでエラーが発生しています)。

名前があって番号がない場合、たとえば: abad 34a(文字 a34aは無視され、エラーが発生するはずのコードで 34 だけに転送されます)、

または、たとえば 2 つ以上の列がある場合abad 34 45(2 番目の数字は無視されます)。

入力データを正しく読み取る方法 (およびイテレータなし)?

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各行で読み取ったすべての文字列を保持して、それらをより簡単に処理できるようにします。次に、次の 3 つのケースがあります。

  • 番号なし: vec.size( ) = 1。
  • 3 つ以上の文字列: 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;
}

ファイル: input.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 に答える