次のことを試してください: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.