Ответ 1
Код cin >> y;
читается только одним словом, а не всей строкой. Чтобы получить строку, используйте:
string response;
getline(cin, response);
Затем response
будет содержать содержимое всей строки.
Вот мой текущий код на С++. Я хотел бы знать, как написать строку кода. Могу ли я использовать 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;
}
}
Код cin >> y;
читается только одним словом, а не всей строкой. Чтобы получить строку, используйте:
string response;
getline(cin, response);
Затем 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;
}
string str;
getline(cin, str);
cin >> ws;
Вы можете использовать функцию getline, чтобы читать всю строку вместо чтения по слову. И cin → ws можно пропустить пробелы. И вы найдете здесь несколько подробностей: http://en.cppreference.com/w/cpp/io/manip/ws