C++ C++;filestream:创建的文件名以奇怪的符号结尾
因此,我一直在使用filestream,我发现了一个问题。每次我试图保存文件时,所创建文件的名称都以以下两个字符结尾:i’。 有办法解决这个问题吗 以下是我得到的: 这是我的密码:C++ C++;filestream:创建的文件名以奇怪的符号结尾,c++,windows,c++11,fstream,C++,Windows,C++11,Fstream,因此,我一直在使用filestream,我发现了一个问题。每次我试图保存文件时,所创建文件的名称都以以下两个字符结尾:i’。 有办法解决这个问题吗 以下是我得到的: 这是我的密码: #include "stdafx.h" #include <iostream> #include <string> #include <stdlib.h> #include <windows.h> #include &l
#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);
}
#包括“stdafx.h”
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
字符串p=“”;
串一些线;
charo[20];
int _tmain(int argc,_TCHAR*argv[]
{
cout=20)
{
cout您正在对所有空格进行预初始化o
,但这是无用的。您应该做的是在文件名的最后一个字符后的字符中写入“\0”。否则数组是不终止的,当您将其用作C字符串时,可能会在结尾处收到“垃圾”
因此:
也就是说,在C++03中,您可能必须从p
获取C字符串,因为流的构造函数尚未接受std::string
:
ofstream save(p.c_str());
(我不记得了,但我认为MSVS允许使用std::string
参数。)为什么不直接将p
传递给流的构造函数?
cout << "Max character length: 19 characters\n\n";
ofstream save(p);
ofstream save(p.c_str());