【问题标题】:displaying a line vs word in c++在 C++ 中显示一行 vs 单词
【发布时间】:2016-03-28 05:18:26
【问题描述】:

我正在处理我的任务,我遇到了一个我想理解的错误(假设这是一个错误,而不仅仅是我过度思考了这个问题)。我当前的输出一次给我一个单词,而我想一次显示一行。这是我的代码:

/*
///////////////////////////////////////////////////////////////////////////
Write a program that creates an array of 100 string objects. Fill the
array by having your program open a (text) file and read one line of the
file into each string until you have filled the array. Display the array
using the format “line #: <string>,” where # is the actual line number
(you can use the array counter for this value) and <string> is the stored
string.
///////////////////////////////////////////////////////////////////////////
*/

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main ()
{
    string story[100];  // create array of 100 string objects
    string filename = "testfile.txt";
    ifstream file(filename); //open file

    // go through array till index 100
    for( int x=0; x<= 100; x++)
    {
       file >> story[x]; // get line and store into array
       cout << "Line " << x << ":" << story[x] << endl; // display
    }

    return 0;
}

这是输出:

I 
ordered
this
sandwich
once
with
paper .....

而我想要这个:

I ordered this sandwich once with paper-thin carrots in it.
I can’t remember what else. 
I tried to recreate it.

【问题讨论】:

  • 尝试删除endl,直到您打印的文本中有句号或句子结尾。

标签: c++ c++11


【解决方案1】:

快速解决方法是将file &gt;&gt; story[x]; 替换为

std::getline(file, story[x]);

file &gt;&gt; story[x] 逐字读取,而std::getline 读取整行。

但是,我会将string story[100]; 更改为std::vector&lt;std::string&gt; story;,因为您事先不知道文件有多少行,并且您可能会超出范围。有了向量,就没有这样的问题了,你可以把push_back放在一个循环里面:

std::string line;
while(std::getline(file, line))
{
    story.push_back(line);
}

【讨论】:

  • 我原本想先使用向量,但这次我想练习使用数组。感谢您的建议 !现在结合我的作业问题的上下文,您会说每行一个单词的原始输出更容易接受还是新输出更容易接受?
  • @KingShahmoo 该作业明确指出您需要逐行阅读,因此您绝对必须使用std::getline。然而,这样的硬件正在自找麻烦,因为数组边界溢出是 C 或 C++ 代码中最糟糕的噩梦之一。至少您要确保在for 循环中读取的行数不超过 100 行,这是可以的(但将 &lt;= 替换为 &lt;,否则您会将 101 行读取到 100 个元素的数组中,并且所有的赌注都是关闭)。
【解决方案2】:

operator&gt;&gt; 的默认分隔符是任何空格。所以file &gt;&gt; story[x]; 会读取一组以空格分隔的字符。

您可以通过更改默认分隔符(过于复杂,但请查看this question)或使用std::getline(file, story[x]); 来解决输入端的问题

或者,如果您想存储单词数组,您可以更改输出端的代码。循环遍历行,添加一个检查,以便一个单词以“。”结尾行结束。在每个单词后输出一个空格,并在行尾输出 std::endl。

【讨论】:

    猜你喜欢
    • 2018-03-03
    • 2015-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    相关资源
    最近更新 更多