C ++如何逐字(字符串)读取文件但将其显示为与文本文件完全一样
C++ How do you read in a file word by word (strings) but display it exactly like the text file
我无法弄清楚如何在将文本输出到 cmdPrompt 时显示换行符。 .text 文件是这样的:
"Roses are red
violets are blue
sugar is sweet
and so are you"
我的循环代码是:
#define newLn "\n"
ifstream ins; //these two are near the top where the programs opens the file
string aString;
while(ins >> aString){
if(aString != newLn){
cout << aString << ' ';
}
else
cout << endl;
}
它可以很好地读取文本,但它只是这样显示:
Roses are red violets are blue sugar is sweet and so are you
我不知道如何像在文本文件中一样显示它(每个语句后都有换行符。我知道你可以只做 while(nextCharacter != newLn) 来读入字符而不是字符串让我难住了。
当您使用格式化提取函数时,例如:
while(ins >> aString){
您丢失了流中存在的所有空白字符。
为了保留空格,您可以使用std::getline
。
std::string line;
while ( getline(ins, line) )
{
std::cout << line << std::endl;
}
如果您需要从行中提取单个标记,您可以使用 std::istringstream
处理文本行。
std::string line;
while ( getline(ins, line) )
{
cout << line << std::endl;
std::istringstream str(line);
std::string token;
while ( str >> token )
{
// Use token
}
}
您正在使用 "fstream extraction operator" 读取文件内容。所以请记住,操作员不会阅读考虑空格和新行,但它认为它们是单词的结尾。所以改为使用 std::getline
.
while(std::getline(ins, aString) )
std::cout << aString << std::endl;
我无法弄清楚如何在将文本输出到 cmdPrompt 时显示换行符。 .text 文件是这样的:
"Roses are red
violets are blue
sugar is sweet
and so are you"
我的循环代码是:
#define newLn "\n"
ifstream ins; //these two are near the top where the programs opens the file
string aString;
while(ins >> aString){
if(aString != newLn){
cout << aString << ' ';
}
else
cout << endl;
}
它可以很好地读取文本,但它只是这样显示:
Roses are red violets are blue sugar is sweet and so are you
我不知道如何像在文本文件中一样显示它(每个语句后都有换行符。我知道你可以只做 while(nextCharacter != newLn) 来读入字符而不是字符串让我难住了。
当您使用格式化提取函数时,例如:
while(ins >> aString){
您丢失了流中存在的所有空白字符。
为了保留空格,您可以使用std::getline
。
std::string line;
while ( getline(ins, line) )
{
std::cout << line << std::endl;
}
如果您需要从行中提取单个标记,您可以使用 std::istringstream
处理文本行。
std::string line;
while ( getline(ins, line) )
{
cout << line << std::endl;
std::istringstream str(line);
std::string token;
while ( str >> token )
{
// Use token
}
}
您正在使用 "fstream extraction operator" 读取文件内容。所以请记住,操作员不会阅读考虑空格和新行,但它认为它们是单词的结尾。所以改为使用 std::getline
.
while(std::getline(ins, aString) )
std::cout << aString << std::endl;