从文本文件中逐行读取单词并转换为int(无限循环或崩溃?)

问题描述 投票:0回答:2

我正在尝试阅读此文本文件:

8 4 4 6 1
8 4 4 6 2
8 4 4 6 3
8 4 4 6 4
8 4 4 6 5
8 4 4 6 6
8 4 4 6 7
8 4 4 6 8
11 4 4 6 3
15 11 13
7 2 1 4 4 
9 4 3 9 9
8 2 1 5 4 
10 1 2 3 4 6 1
6 1 1 2 5 3 2
13 1 1 2 10 3 8 
11 2 11 10 7

并完全按照控制台所示进行打印(以确保获得所有输入)。

但是,由于某种原因,我的代码在第一行中读取后崩溃了。我什至无法终止调试器。

这是我的代码:

while(getline(inFile, buffer)){
    buffer2 = strdup(buffer.c_str());
    line = strtok(buffer2, " ");
    size = atoi(line);
    cout << size << " ";

    while(line!=NULL){
        line = strtok(NULL, " ");
        cout << line << " ";
    }

    cout << "~~~~~~~~~" << endl;
}
c++ while-loop strtok strdup
2个回答
2
投票
如果要使用C ++,则应利用它,使用字符串流:

#include <fstream> #include <sstream> #include <iostream> using namespace std; //for sample purposes, should not be used int main() { int temp, count = 0, sum = 0, total = 0; string buffer; ifstream myFile("in.txt"); if (!myFile.is_open()) cout << "No file" << endl; else{ while(getline(myFile, buffer)){ sum = 0; stringstream ss(buffer); while(ss >> temp){ count++; //number count sum += temp; //line sum cout << temp << " "; } total += sum; //total sum cout << endl << "count: " << count << endl << "sum: " << sum << endl << "total: " << total << endl << endl; } myFile.close(); } cout << "~~~~~~~~~" << endl; }


1
投票
您正在泄漏strdup()分配的内存。使用free()完成后,需要致电buffer2

但更重要的是,当没有更多令牌返回时,strtok()返回NULL。但是将NULL char*指针传递给operator<<

undefined behavior。您的while循环恰好在到达每一行的末尾时进行操作,因此anything可能发生,包括崩溃。

尝试以下方法:

while (getline(inFile, buffer)) { buffer2 = strdup(buffer.c_str()); if (buffer2 != NULL) { line = strtok(buffer2, " "); while (line != NULL) { size = atoi(line); cout << size << " "; line = strtok(NULL, " "); } free(buffer2); } cout << "~~~~~~~~~" << endl; }

话虽这么说,您为什么要全部使用strdup()strtok()atoi()?您正在编写C ++代码,应该使用C ++语义而不是C语义。例如,您可以改用std::istringstream,例如:

while (getline(inFile, buffer)) { istringstream iss(buffer); while (iss >> size) { cout << size << " "; } cout << "~~~~~~~~~" << endl; }

© www.soinside.com 2019 - 2024. All rights reserved.