how to read the formatted file in C++
I have the following format. Each line has two integers and the file is ended by "*". How can I read the two numbers from the file. Thanks.
4 5
7 8
78 89
* //end of file
Edit
I know read the two numbers but do not know how to deal with "*". If I store each number as integer type and read them by cin
. But The last line is a string type. So the problem is that I read it as a integer but it is string, I do not how to judge whether it is * or not.
My code was as follows (it is obviously incorrect):
string strLine,strCh开发者_运维技巧ar;
istringstream istr;
int a,b;
while(getline(fin,strChar))
{
istr.str(strLine);
istr>> ws;
istr>>strChar;
if (strChar=="*")
{
break;
}
istr>>a>>b;
}
You can simply pull the numbers from the ifstream
object until it fails.
std::ifstream fin("file.txt");
int num1, num2;
while (fin >> num1 >> num2)
{
// do whatever with num1 and num2
}
I preffer to use good old fscanf() method, see a simple and straightforward example on MSDN.
- As first step read entire line into a string buffer
- Check whether it equals to "*"
- If not - use sscanf() to parse two integers
The solution is to use std::istream
to read the file line by line. Then, process each input line and store the numbers into a list.
// open the file.
std::string path = "path/to/you/file";
std::ifstream file(path.c_str());
if (!file.is_open()) {
// somehow process error.
}
// read file line by line.
std::vector< std::pair<int,int> > numbers;
for (std::string line; std::getline(file,line);)
{
// prepare to parse line contents.
std::istringstream parser(line);
// stop parsing when first non-space character is '*'.
if ((parser >> std::ws) && (parser.peek() == '*')) {
break;
}
// store numbers in list of pairs.
int i = 0;
int j = 0;
if ((parser >> i) && (parser >> j)) {
numbers.push_back(std::make_pair(i, j));
}
}
精彩评论