首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在C++中读取.txt文件

如何在C++中读取.txt文件
EN

Stack Overflow用户
提问于 2018-09-23 06:50:35
回答 1查看 105关注 0票数 0

我们有一个.txt,里面有这个

代码语言:javascript
复制
PR-ATT-2 Sep 5 2018 Dec 15 2020
LE-GE-3 Oct 15 2019 Jan 20 2021

在我们的代码中,我们尝试将第一行设置为字符串

代码语言:javascript
复制
#include <string>
#include <array>
#include <cstdlib>
#include <fstream>
#include <istream>
#include <iostream>

using namespace std;

int main(int argc, char* argv[]) {
    ifstream projin;
        projin.open(argv[1], ios::in);
        // Making sure the file opened correctly
        if ((projin.is_open()) == false) {
            cout << "There was an error opening the file";
            return 1;
        } else {
            string projectline;
            getline(projin, projectline);
            cout << projectline << " ";
            projin.close();
            return 2;
        }
    return 0;
}

这不会返回任何内容。但是如果代码看起来像这样

代码语言:javascript
复制
#include <string>
#include <array>
#include <cstdlib>
#include <fstream>
#include <istream>
#include <iostream>

using namespace std;

int main(int argc, char* argv[]) {
    ifstream projin;
        projin.open(argv[1], ios::in);
        // Making sure the file opened correctly
        if ((projin.is_open()) == false) {
            cout << "There was an error opening the file";
            return 1;
        } else {
            string projectline;
            getline(projin, projectline);
            cout << "Hello my name is Alejandro, and my favorite word is 
pneumonoultramicroscopicsilicovolcanoconiosis " << projectline << " ";
            projin.close();
            return 2;
        }
    return 0;
}

这返回“您好,我的名字是Alejandro,我最喜欢的词是肺显微镜硅火山柯萨奇病PR-ATT-2 Sep 5 2018 D”。

我们这一生都搞不清楚到底发生了什么。

EN

回答 1

Stack Overflow用户

发布于 2018-09-23 07:14:41

我们将其更改为while循环,该循环打印该行直到文件末尾,这给出了我们想要的输出。

代码语言:javascript
复制
ifstream projin;
projin.open(argv[1], ios::in);
// Making sure the file opened correctly
if ((projin.is_open()) == false) {
    cout << "There was an error opening the file";
    return 1;
} else {
    string projectline;
    while (getline(projin, projectline)) {
        cout << projectline << endl;
    }
    projin.close();
    return 2;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52461529

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档