基本上,我試圖從一行代碼中獲取三件事,從 .txt 檔案中讀取。這將重復,但現在我只需要知道如何獲得一行。我正在閱讀的行看起來像這樣:
Biology $11 12
所以我想得到一個字串和兩個整數,并完全忽略 $ (注意,我不能更改 .txt 檔案,所以我必須保留 $ )
所以如果我有
string subject;
int biologyscores[25];
我的代碼是:
int biologyscores[25]; //array to store the integer values
std::string subject; //string to store the subject the scores are for
std::ifstream infile("myScores.txt"); //declare infile to read from "myScores.txt"
infile >> subject >> biologyscores[0] >> biologyscores [1]; //read into string and int array
因此該字串將用于檢查這些分數是針對哪個科目的,分數本身將存盤在一個陣列 bioscores 中,彼此相鄰索引。
問題是在此代碼執行后,subject = "Biology" 這是所需的,但索引 0 和 1 處的 bioscores 似乎都有垃圾數字,而不是我想要讀入的數字。
uj5u.com熱心網友回復:
您可以使用一個虛擬字符變數來“拾取” $ 字符:
char dummy_char;
infile >> subject >> dummy_char >> biologyscores[0] >> biologyscores [1]; //read into string and int array
uj5u.com熱心網友回復:
您可以使用seekg和tellg
std::fstream infile("myScores.txt"); //declare infile to read from "myScores.txt"
int temp;
infile >> subject; //read into string
temp=infile.tellg(); //to get the position of $
infile.seekg(temp 1);// to move one step forward
infile>> biologyscores[0] >> biologyscores [1];//now you can read the int values
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/373413.html
上一篇:函式中的元組比較
