如何在c++中使用cin将带有空格的文本插入到文本文档中
How can I insert text WITH SPACES into a text document in C++ using cin?
我对编程非常陌生,我正在尝试用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;
}
相关文章:
- 2D数组来自文本输入,中间有空格
- 从文本文件中读取所有内容,直至空格
- 使用空格分隔符从文本文件将对象读入数组
- 从文本文件中读取数据并删除所有换行符空格,并在 C++ 控制台中显示
- 崇高文本 3 - 在终端中编译并运行 C++ 程序(路径包含空格)
- 非空格分隔的文本文件到 2D 矢量
- 从文件中读取带有空格和数字数据的文本
- 通过删除C 中的评论,额外的空格和空白行,从文本文件中换成元素
- 将文本写入文件,包括空格
- 使用 + 和空格将字符串与文本串联
- 文本文件解析C++|用空格分隔
- 打开文本文件并读取一个带有空格的字符串,然后将两个独立的int放入一个结构中
- 知道文本文件中的列数,用空格或制表符分隔
- 有效地检查文本文件是否完全由空格c++组成
- C++ 从空格分隔的文本文件中填充字符串向量
- 将具有多个空格的字符串添加到文本文件
- 如何从文本文件 c++ 中读取具有一定长度空格的输入字符串
- 以C++打印出文本文件中的空格
- 读取空格将数字从文本文件分隔到整数数组 (C++)
- 将包含空格的文件中的文本存储为字符串