我正在用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
(34a
中的字母a被忽略并在我的代码中转移到34而应该触发错误),
或者如果有超过2列,例如abad 34 45
(忽略第二个数字)。
如何正确读取输入数据(没有迭代器)?
答案 0 :(得分:2)
试试这个:
if( !(sline >> str >> num >> std::ws) || sline.peek() != EOF ) {
//throw error
}
std::ws
是一个流操纵器,用于提取num
后面的可能空格。包括<iomanip>
。接下来,检查流中的偷看是否返回EOF。如果没有,你有更多的输入等待,这是一个错误。
答案 1 :(得分:1)
请尝试以下操作:继续std::vector
每行中读取的所有字符串,以便您能够更轻松地处理它们。然后,有三种情况:
代码:
#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.