【问题标题】:C++ return string keeps getting junkC ++返回字符串不断变得垃圾
【发布时间】:2013-04-08 23:36:06
【问题描述】:

为什么这里的返回字符串上面有各种垃圾?

string getChunk(ifstream &in){
char buffer[5];
for(int x = 0; x < 5; x++){
    buffer[x] = in.get();
    cout << x << " " << buffer[x] << endl;
}
cout << buffer << endl;
return buffer;
}

ifstream openFile;
openFile.open ("Bacon.txt");
chunk = getChunk(openFile);
cout << chunk;

即使我的调试表明我的缓冲区正在填充正确的字符,我在字符串的末尾也有一堆垃圾。

谢谢,c++ 比 Java 难很多。

【问题讨论】:

    标签: c++ file buffer


    【解决方案1】:

    您需要 NULL 终止缓冲区。使缓冲区大小为 6 个字符并将其初始化为零。像现在一样只填写前 5 个位置,不要理会最后一个。

    char buffer[6] = {0};  // <-- Zero initializes the array
    for(int x = 0; x < 5; x++){
        buffer[x] = in.get();
        cout << x << " " << buffer[x] << endl;
    }
    cout << buffer << endl;
    return buffer;
    

    或者,保持数组大小不变,但使用string constructor,它采用char * 和从源字符串中读取的字符数。

    char buffer[5];
    for(int x = 0; x < 5; x++){
        buffer[x] = in.get();
        cout << x << " " << buffer[x] << endl;
    }
    cout << buffer << endl; // This will still print out junk in this case
    return string( buffer, 5 );
    

    【讨论】:

    • 谢谢,我一会儿试试。
    猜你喜欢
    • 2013-10-30
    • 2013-02-07
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2020-08-30
    • 1970-01-01
    相关资源
    最近更新 更多