讀取數字線所以在我的txt文件我有這個如何從txt文件
1,200,400
2,123,321
3,450,450
4,500,250
每一次我都會有3個數字相同的數字,我需要閱讀它們,並將它們保存在一些變量,誰能幫助我如何做到這一點,因爲主要是我得到的教程展示瞭如何讀取字符,但如果我試圖把它們寫在變量中,我得到一些奇怪的數字...
讀取數字線所以在我的txt文件我有這個如何從txt文件
1,200,400
2,123,321
3,450,450
4,500,250
每一次我都會有3個數字相同的數字,我需要閱讀它們,並將它們保存在一些變量,誰能幫助我如何做到這一點,因爲主要是我得到的教程展示瞭如何讀取字符,但如果我試圖把它們寫在變量中,我得到一些奇怪的數字...
std::fstream myfile("filename.txt", std::ios_base::in);
int a ,b,c;
char ch; //For skipping commas
while (myfile>> a >> ch >> b>> ch >>c)
{
// Play with a,b,c
}
myfile.close();
如果你想閱讀數字,你需要.ignore()
這個逗號(或者把它解壓到一個char
)。如果你想保存的元組,你可以使用std::vector
std::tuple<int, int, int>
的:
std::vector<std::tuple<int,int,int>> myNumbers;
int number1, number2, number3;
while(((file >> number1).ignore() >> number2).ignore() >> number3){
myNumbers.push_back(make_tuple(number1, number2, number3));
}
最簡單的方法(我猜)是讀取逗號進入虛擬焦炭變量。
int num1, num2, num3;
char comma1, comma2;
while (file >> num1 >> comma1 >> num2 >> comma2 >> num3)
{
...
}
讀了逗號入變量comma1
和comma2
那麼你可以忽略它們,因爲所有你真正感興趣的是數字。
我真的很喜歡這個,但它只讀取1行,我怎麼能讓它讀取更多然後1行? – Kebapmanager
@ user2850409它應該讀取多行,這就是我使用while循環的原因。也許你應該問一個新問題,如果你有麻煩。 – john
您的文件格式與CSV文件格式相同,因此您可以使用它。
從http://www.cplusplus.com/forum/general/13087/
ifstream file ("file.csv");
string value;
while (file.good())
{
getline (file, value, ','); // read a string until next comma: http://www.cplusplus.com/reference/string/getline/
cout << string(value, 1, value.length()-2); // display value removing the first and the last character from it
}
cplusplus.com是一個糟糕的習慣和編碼風格的來源。這是一個例子。 – Manu343726
但我不需要顯示我的價值,我需要在我的代碼中使用它來構建我的關卡,這使得第一個和最後一個字符成爲問題。 – Kebapmanager
什麼輸入逗號? – john
因爲簡單,我真的很喜歡這個,但我怎樣才能讓它讀取直到文件的結尾,就像所有的行不只是一個。 – Kebapmanager
@ user2850409只要流處於良好狀態,while循環將讀取文件,即直到文件結尾 – P0W