保存到文件时,会忽略空白后的单词
when saving to file, words after white space are ignored
我一直在努力保存到文件中,结果就是这样。唯一的问题是,空格后的任何内容都会被忽略(如果你键入"johnsmith"(,它会打印出来("最后一个使用这个文件的人是:john"(我使用GNUGCC编译器的代码块。这是代码:
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main()
{
string name;
ofstream saveData;
ifstream Data;
Data.open("Info.data", ios::binary);
Data >> name;
Data.close();
cout << "The last person to use the file was " << name << endl;
cout << "What is your name?" << endl;
cin >> name;
saveData.open("Info.data", ios::binary);
saveData << name;
cout << name << endl;
system("PAUSE");
saveData.close();
return 0;
}
感谢
对于字符串,ifstream
(包括cin
(的对象从开始到第一个空格使用输入,空格为space、TAB和NELINE。因此,您应该使用getline
而不是cin >>
试试这个:
Data.open("Info.data");
getline(Data, name);
Data.close();
和
cout << "What is your name?" << endl;
//cin >> name;
getline(cin, name);
更新:
顺便说一下,在你的代码中之后
Data.open("Info.data", ios::binary);
你使用
Data >> name;
所以,以二进制模式打开的流被>>
读取——这不是很好。
相关文章:
- 文本文件中的单词链表
- 无法通过空白将文本文件行分隔为矢量
- 在指针的帮助下,文本文件中单词的频率
- 如何根据单词在文本中出现的概率输出单词
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- 如何用for循环在c++中生成单词三角形
- 将数字转换为单词
- 使用if-else将数字转换为单词
- C++-字符串是否包含一个带有简单循环的单词
- 使用单词"not"作为C ++类的名称会导致VS2019错误
- 由cin中的字符串中未捕获空白引起的分割错误
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数
- C++为一串单词添加空格
- 在C++中查找(奇怪的)字符串中的单词
- 尝试从 XamlApplication 编译 C++/WinRT 空白应用程序时,我收到未解析的外部符号 winrt_make_*
- 在文件中搜索字符串(逐行),忽略单词之间空白的大小
- 保存到文件时,会忽略空白后的单词
- Wordwap函数修复保留单词之间的空白