如何在c++中使用cin将带有空格的文本插入到文本文档中

How can I insert text WITH SPACES into a text document in C++ using cin?

本文关键字:文本 空格 文档 插入 c++ cin      更新时间:2023-10-16

我对编程非常陌生,我正在尝试用c++编写一个程序,该程序将用户输入的文本转换为HTML代码并将该代码输出到文本文件上。我已经写了基本的程序,它工作得很好。我唯一的问题是能够在单词之间输入空格。例如,如果你要在程序中输入"HELLO WORLD",它只会在文本文件中显示"HELLO"。我明白问题是什么,cin将阅读文本并停止在空白,但我想找出是否有任何方法?如有任何建议,不胜感激,谢谢。

我写的代码:

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <string.h>
using namespace std;
int main()
{
    ifstream( inputFile );
    ofstream( outputFile );
    char title[500];
    char heading[500];
    char color[10];
    char body[5000];
    outputFile.open("html.txt");
    cout << "Please enter a title: ";
    cin >> title;
    cout << "Please enter a heading: ";
    cin >> heading;
    cout << "What color would you like your heading to be? ";
    cin >> color;
    cout << "Please enter the body: ";
    cin >> body;
    outputFile << "<!doctype html> " << "n" << "<html> " << "n" << "<head> " << "<title> " << title << " " << "</title> " << "</head>" << "n"
           << "<body> " << "n" << "<h1> " << "<center> " << "<font color="" << color << ""> " << heading << " " << "</font> " << "</center> " << "</h1> " << "n"
           << body << " " << "n" << "</body> " << "n" << "</html> " << "n";

    outputFile.close();
    system("PAUSE");
    return 0;
}

在您的代码中,您要读取输入的整行,就我对您的问题的理解而言

cout << "Please enter the body: ";
std::getline(cin,body);

代替将body声明为普通的char数组(char body[5000];),您必须使用std::string代替:

std::string body;

这样你就不用担心估计和保留你能得到的最大可能的输入长度。

注意:
上面的示例只允许您输入一行HTML文本,如果您不想有多行输入,则需要选择不同的行分隔符(而不是默认的'n'),或者将后续输入累积到body,直到输入空行或其他适当的结束标记:

std::string body;
cout << "Please enter the body (stop entering a blank line): ";
std string line;
std::cin.clear(); // Get rid of all previous input state
do {
    std::getline(cin,line);
    if(line.empty()) {
        break; // Stop the input loop
    } 
    else {
        body += line + "n"; // accumulate the entered input to 'body'
    }
} while(1);

尝试使用cin.getline(body,5000)

你也许应该去看看。Getline函数…请看这个例子(在stackoverflow上找到)

#include <iostream>
using namespace std;
int main () {
  char name[256], title[256];
  cout << "Enter your name: ";
  cin.getline (name,256);
  cout << "Enter your favourite movie: ";
  cin.getline (title,256);
  cout << name << "'s favourite movie is " << title;
  return 0;
}