您可以使用這樣的事情:
#include <iostream>
#include <fstream>
#include <string>
using std::string;
using std::ifstream;
using std::cout;
using std::cerr;
using std::endl;
int main()
{
ifstream infile;
//infile.open("file.csv");
infile.open("C:\\Users\\Kraemer\\Desktop\\test.csv");
string row;
while (getline(infile, row))
{
int sum = 0; //number of commas
size_t pos = 0; //Position in row
//As long as we didn't find 10 commas AND there is another comma in this line
while(sum < 10 && (pos = row.find(',', pos)) != string::npos)
{
//Comma found
sum++;
//Set position behind the comma
pos++;
}
//When we come here sum is always <= 10
if(sum == 10)
{ //10 commas found
cerr << "Found 10 commas" << endl;
}
else
{
cerr << "Did not find enough commas in line" << endl;
}
}
return 0;
}
你也應該注意到,getline(infile, row)
也將在EOF
是在包含數據的最後一行失敗。 因此,您需要在infile.eof()
返回true
時檢查最後一個讀取行,或者確保輸入數據以空行結束。
要提取的數字第十逗號後,你可以做這樣的事情:
if (sum == 10)
{ //10 commas found
cerr << "Found 10 commas" << endl;
if (pos < row.size())
{
char digitAsChar = row[pos];
if (digitAsChar >= '0' && digitAsChar <= '9') // Valid digit
{
int digitAsInt = digitAsChar - '0'; //Convert from char to int
cout << "Found digit " << digitAsInt << endl;
}
else
{
cerr << "Character '" << digitAsChar << "' is no digit." << endl;
}
}
else
{
cerr << "10th comma is at the end of the line - no digit found" << endl;
}
}
else
{
cerr << "Did not find enough commas in line" << endl;
}
輸入:
,,,,,,,,,,1
,,,,,,,,,,2
,,,,,,,,,,3
,,,,,,,,,,4
,,,,,,,,,,5
,,,,,,,,,,f
,,,,,,,,,,
,,,,,,,,,,8
,,,,,,,,,9
,,,,,,,10
輸出:
Found 10 commas
Found digit 1
Found 10 commas
Found digit 2
Found 10 commas
Found digit 3
Found 10 commas
Found digit 4
Found 10 commas
Found digit 5
Found 10 commas
Character 'f' is no digit.
Found 10 commas
10th comma is at the end of the line - no digit found
Found 10 commas
Found digit 8
Did not find enough commas in line
Did not find enough commas in line
不工作*如何*? – Biffen
將'int sum = 0;'放在while循環中。 –
......也許是因爲你只是反覆調用'find()',每次只能找到相同的逗號(第一個)。 *而且*你永遠不會在任何地方保存找到的位置。 – Biffen