这是我目前的C++代码.我想知道如何编写一行代码.我还会使用cin.getline(y)或不同的东西吗?我已经检查过,但找不到任何东西.当我运行它时,它完美地工作,除了它只键入一个单词而不是我需要输出的整行.这是我需要帮助的.我在代码中概述了它.
谢谢你的帮助
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <fstream>
using namespace std;
int main()
{
char x;
cout << "Would you like to write to a file?" << endl;
cin >> x;
if (x == 'y' || x == 'Y')
{
char y[3000];
cout << "What would you like to write." << endl;
cin >> y;
ofstream file;
file.open("Characters.txt");
file << strlen(y) << " Characters." << endl;
file << endl;
file << y; // <-- HERE How do i write the full line instead of one word
file.close();
cout << "Done. \a" << endl;
}
else
{
cout << "K, Bye." << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
yba*_*kos 67
代码cin >> y;只读一个字,而不是整行.要获得一条线,请使用:
string response;
getline(cin, response);
Run Code Online (Sandbox Code Playgroud)
然后response将包含整行的内容.
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <string>
int main()
{
char write_to_file;
std::cout << "Would you like to write to a file?" << std::endl;
std::cin >> write_to_file;
std::cin >> std::ws;
if (write_to_file == 'y' || write_to_file == 'Y')
{
std::string str;
std::cout << "What would you like to write." << std::endl;
std::getline(std::cin, str);
std::ofstream file;
file.open("Characters.txt");
file << str.size() << " Characters." << std::endl;
file << std::endl;
file << str;
file.close();
std::cout << "Done. \a" << std::endl;
}
else
std::cout << "K, Bye." << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
string str;
getline(cin, str);
cin >> ws;
Run Code Online (Sandbox Code Playgroud)
您可以使用getline函数读取整行而不是逐字读取。而cin>>ws是用来跳过空格的。您可以在此处找到有关它的一些详细信息:http : //en.cppreference.com/w/cpp/io/manip/ws