输出不是我输入的内容。它是 --> (畳慨汩朠灵慴찀쳌쳌쳌)
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
char x[20];
cout << "enter something\n";
cin.getline(x,20);
ofstream o("d:/tester.txt");
//o.write( (char*)&x , sizeof(x) );
for(int i = 0 ; i<=19 ; i++ ) {
o.put(x[i]);
}
}
我没有在程序期间输入的文件中获得该输出。例如。写入suhail gupta时,输出为畳哀汩朠灵恐惧찀쳌쳌쳌
。
代码有什么问题? 即使我使用 o.write( (char*)&x , sizeof(x) );
(注释语句) 我得到相同的输出。
原因是什么?
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
char x[20];
cout << "enter something\n";
cin.getline(x,20);
ofstream o("d:/tester.txt");
//o.write( (char*)&x , sizeof(x) );
for(int i = 0 ; i<=19 ; i++ ) {
o.put(x[i]);
}
}
I am not getting that output in the file the one which i enter during program . for eg. the output is 畳慨汩朠灵慴찀쳌쳌쳌
on writing suhail gupta.
What is the problem with the code ? Even when i use o.write( (char*)&x , sizeof(x) );
(the commented statement) i get the same output.
What is the reason?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的程序涉及未定义的行为。
x
数组未完全初始化,您从未初始化的索引中读取。此外,您总是写入 20 个字节,与从用户处读取的内容无关。我猜你使用的是记事本之类的文本编辑器。后者在尝试猜测编码时有错误。它似乎猜测文件是 UTF16 并显示
20/2 == 10
字符。要解决此问题,请将用户输入的字符数准确存储到文件中。使用
std::string
使其更容易。编辑:C++ 方式:
Your program involves undefined behavior. The
x
array is not fully initialized and you read from the uninitialized indices. Besides, you always write 20 bytes, independent of what you read from the user.I guess you use some text editor like Notepad. The latter has bugs when trying to guess the encoding. It appears that it guesses the file is UTF16 and displays
20/2 == 10
characters instead.To solve the problem, store to the file exactly the number of characters entered by the user. Use
std::string
to make it easier.Edit: The C++ way: