C ++返回字符串不断变得垃圾 [英] C++ return string keeps getting junk

查看:52
本文介绍了C ++返回字符串不断变得垃圾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why does the return string here have all sorts of junk on it?

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;

我在字符串的末尾有很多垃圾,即使我的调试程序说我的缓冲区中充满了正确的字符。

I get a load of junk in the string where it has junk on the end of it, even though my debug says that my buffer is being filled with the correct characters.

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

Thanks, c++ is a lot harder than Java.

推荐答案

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

You need to NULL terminate the buffer. Make the buffer size 6 characters and zero initialize it. Fill only the first 5 locations as you're doing now, leave the last one alone.

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;

或者,保持数组大小不变,但是使用字符串构造器,它使用 char * 和字符数从源字符串读取。

Alternately, leave the array size the same, but use the string constructor that takes a char * and number of characters to read from the source string.

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 );

这篇关于C ++返回字符串不断变得垃圾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆