【问题标题】:C++ vector::front not workingC++ 向量::front 不工作
【发布时间】:2018-03-07 07:14:30
【问题描述】:

我正在尝试从文本文件中读取这些行,然后将每一行分解为一个单词向量。接下来,我需要从每个向量中获取第一个单词。以下是我的代码

#include<bits/stdc++.h>
using namespace std;

int main (){
    ifstream inputFile("input.txt");
    vector<string> words;
    string line, piece;

    while( getline(inputFile, line) ){

        istringstream lineStream(line);

        while( getline(lineStream, piece, ' ') ){
            words.push_back(piece);
        }

        // this does not work
        cout << words.front() << endl;

        /*
        // this works fine
        for(unsigned int i=0; i<words.size(); i++){
            cout << words[i] << endl ;
        }
        */

        words.clear();
    }
    return 0;
}

这是文本文件包含的内容

Read the lines from a file
Break each line into words
print the 1st word from each of those lines

这给了我以下错误

此行导致错误

cout << words.front() << endl;

我需要这样的输出

Read
Break
print

请有人帮忙!

【问题讨论】:

  • 您尝试cout &lt;&lt; words[0] &lt;&lt; endl; 获取第一个元素吗?您还应该确保向量不为空。
  • 您几乎肯定不应该包含bits/stdc++.h - 以bits 开头的任何内容都是内部“特定于实现”的标头,并且a)不可移植,b)不一定“完整”。
  • 除了@mch:words[0] 以及words.front() 如果words.empty() 返回true 将失败(可能崩溃)。因此,这应该事先检查。
  • 非空技巧奏效了。非常感谢@mch
  • 你真的应该避免using namespace std - 这是一个坏习惯,当你不期待它时can silently change the meaning of your program。习惯于使用命名空间前缀(std 故意很短),或者将只是您需要的名称 导入到最小的合理范围。此外,在此处发布代码时请坚持使用标准 C++ 标头 - &lt;bits/stdc++.h&gt; 是特定于平台的,会减少可能回答的人数。

标签: c++ vector file-handling


【解决方案1】:

您确定 std::vector&lt;string&gt; words 确实被填充到 while 循环中了吗?因为如果不是这样,您将尝试访问一个空向量,从而导致崩溃。

在访问front()之前进行检查,如下所示:

if( !words.empty() )
    cout << words.front() << endl;

这将确保只有在向量中填充了有意义的内容时才能访问front()

【讨论】:

    猜你喜欢
    • 2015-08-17
    • 1970-01-01
    • 2012-06-16
    • 2011-11-23
    • 2022-01-24
    • 1970-01-01
    • 2019-01-27
    • 2020-06-01
    • 1970-01-01
    相关资源
    最近更新 更多