C++ Input to .txt

C++ Input to .txt

本文关键字:txt to Input C++      更新时间:2023-10-16

我在一个笔记本程序上工作了几天,遇到了一个我似乎无法解决的问题。下面的代码运行得很好,但是最后的结果让我摸不着头脑。

#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;
}

祝你的笔记本程序好运!