所以我一直在处理文件流,但我遇到了一个问题。每次我尝试保存文件时,创建的文件的名称都以这两个字符结尾: i' 。 有什么办法可以解决这个问题吗?
这是我得到的:
这是我的代码:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdlib.h>
#include <windows.h>
#include <cstdlib>
#include <stdio.h>
#include <cstdio>
#include <fstream>
using namespace std;
string p = "";
string some_string;
char o[20];
int _tmain(int argc, _TCHAR* argv[])
{
cout << "Choose a name for your file: ";
getline(cin, p);
if (p.length() >= 20)
{
cout << "Max character length: 20 characters\n\n";
system("pause");
exit(EXIT_SUCCESS);
}
else
{
ofstream out("resources");
out.trunc;
out << p;
out.close();
}
for (int i = 0; i < 20; i++)
{
o[i] = ' ';
}
for (unsigned int t = 0; t < p.length(); t++)
{
o[t] = p.at(t);
}
ofstream save(o);
save << some_string;
save.close();
cout << "A new file named: '" << p << "' was created\n";
Sleep(2500);
}
(我使用的是 Microsoft VS 2013)
提前致谢!
最佳答案
您正在为所有空格预初始化 o
,但这没有用。您应该做的是在文件名的最后一个字符之后的字符中写入一个“\0”。否则,该数组是非终止的,当您将它用作 C 字符串时,您可能会在末尾得到“垃圾”。
所以:
for (unsigned int t = 0; t < p.length(); t++) {
o[t] = p.at(t);
}
o[p.length()] = '\0';
您还应该将错误消息更改为以下内容,以使其准确无误:
cout << "Max character length: 19 characters\n\n";
如果你对 o
使用 std::string
会容易得多,那么你就不必乱用 char
数组和循环。事实上,由于 o
只是 p
中字符的拷贝,您可以完全忘记 o
而只使用 p
本身:
ofstream save(p);
也就是说,在 C++03 中,您可能必须从 p
获取 C 字符串,因为 ofstream
构造函数不接受 std: :string
还:
ofstream save(p.c_str());
(我不记得了,但我认为 MSVS 无论如何都允许使用 std::string
参数。)
关于C++ 文件流 : Created filename ends with weird symbols,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25941176/