C++ Input to .txt
C++ Input to .txt
我在一个笔记本程序上工作了几天,遇到了一个我似乎无法解决的问题。下面的代码运行得很好,但是最后的结果让我摸不着头脑。
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
int main ()
{
time_t now = time(0);
tm *ltm = localtime(&now);
std::string note;
int day = ltm->tm_mday;
int month = 1 + ltm->tm_mon;
int year = 1900 + ltm->tm_year;
std::string d = std::to_string(day);
std::string m = std::to_string(month);
std::string y = std::to_string(year);
std::string text;
std::getline(std::cin, text);
if(text.find("take ") != std::string::npos &&
text.find("note ") != std::string::npos)
{
{
std::ofstream myfile ("C:\Users\Filepath\" + m + d + y + ".txt");
if (myfile.is_open())
{
std::cin >> note;
myfile << note << "n";
}
else
{
std::cout << "Could not create note. Write it down." << endl;
}
}
}
system("pause");
return 0;
}
如果我在命令提示符中输入"Give invite to Sander Cohen."
当我打开文本文件时,里面只有"Give"
谢谢你的帮助!
有一个问题,cin
只输入第一个单词,而不是整行。这是一个非常简单的修复,这是你的新代码:
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
int main ()
{
time_t now = time(0);
tm *ltm = localtime(&now);
std::string note;
int day = ltm->tm_mday;
int month = 1 + ltm->tm_mon;
int year = 1900 + ltm->tm_year;
std::string d = std::to_string(day);
std::string m = std::to_string(month);
std::string y = std::to_string(year);
std::string text;
std::getline(std::cin, text);
if(text.find("take ") != std::string::npos &&
text.find("note ") != std::string::npos)
{
{
std::ofstream myfile ("C:\Users\Filepath\" + m + d + y + ".txt");
if (myfile.is_open())
{
std::getline(std::cin, note); // getline
myfile << note << "n";
}
else
{
std::cout << "Could not create note. Write it down." << std::endl; // make sure you have std:: befor endl
}
}
}
system("pause");
return 0;
}
祝你的笔记本程序好运!
相关文章:
- "error: no matching function for call to"构造函数错误
- 调用专用模板时出错"no matching function for call to [...]"
- C++ Singleton - Prevent ::instance() to variable
- 如何将 txt 文件中的行分隔为组件C++
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- Visual Studio Code "undefined reference to `WinMain@16'"
- 使用 GCC 卸载的 OpenMP 卸载失败,并出现"Ptx assembly aborted due to errors"
- 一种在C++中读取TXT配置文件的简单方法
- 如何解决"invalid conversion from 'char' to 'const char*'"
- 如何修复此iFile以将.txt输出到控制台
- 使用 MATLAB 编码器生成C++代码:编译错误"undefined reference to `rgb2gray_tbb_real64'"
- 无法打开.txt文件
- 尝试链接我的着色器时,我收到错误代码"error c5145 must write to gl_position"
- Python str to C++ to Python str
- CMakeLists.txt中的命名空间表示法
- Arduino从Txt读取整数
- 为什么创建友元类的实例会导致"undefined reference to"错误?
- 如何使用CLion在Mac上创建一个新的.txt文件
- C++ Input to .txt