如何在C++中将不定大小文件中的多个整数读取到多个变量中?
问题分析与修复
核心错误原因
- 错误使用
inFile.get()读取整数:get()方法会读取文件中的单个字符并返回其ASCII码值,而非字符对应的数字。比如文件里的字符'5'会被读取为ASCII值53,换行符对应10,空格对应32,这直接导致你读取的所有数值完全不符合预期。 - 流操作符方向搞反:
numPros << inFile.get();是错误的语法,输入流的读取操作应该是输入流 >> 变量,而非反过来。
修复后的代码
// Let user give input file cout << "Enter the input file name: "; string in; cin >> in; cout << "\n\n"; // Exit program if input file can't be opened ifstream inFile; inFile.open(in); if (!inFile) { cout << "Input file invalid or failed to open.\n\n"; return 2; } // Get the number of processes from the input file inFile >> numPros; // 修正:使用>>运算符读取整数 // Create a list of jobs from the input file for (int i = 0; i < numPros; i++) { timer = 1000; int id, at, ct; inFile >> id >> at >> ct; // 修正:用>>连续读取三个整数,自动跳过空白 cout << id << " "; if (at < timer) timer = at; Job j(id, at, ct); jobList.push_back(j); }
关键说明
>>运算符会自动跳过文件中的所有空白字符(包括空格、换行符、制表符),直接读取有效的整数内容,完美匹配你的文件格式。- 修正后第一行的
5会被正确存入numPros,后续每行的三个整数也会依次被读取到id、at、ct中,不管它们是否在同一行(即使换行或有多余空格也不影响)。
内容的提问来源于stack exchange,提问作者user21357599
相关产品推荐
相关产品推荐

