繁体   English   中英

如何从txt文件创建字符串

[英]how to create a string from a txt file

我正在尝试获取一个 txt 文件并从中创建一个字符串,但我不知道如何使它工作。

我曾尝试使用getline字符串 function 但它没有按照我使用它的方式创建正确的字符串。

ifstream inFile("somefile.txt");
string mystring;

while (getline(inFile, mystring)) {

    cout << mystring << endl;
}

我的程序的最终目标是逐行读取 a.txt 文件并编辑每一行,使其宽度为 100 个字符。 这第一部分似乎是我目前唯一遇到问题的地方。

这可能是由于 stream object 无法找到或打开文件。 尝试检查inFile是否良好或有效。

#include <iostream>
#include <string>
#include <fstream>
using std::cout;
using std::ifstream;
using std::string;
using std::endl;


int main() {
    ifstream inFile("example.txt");
    string mystring;
    if( inFile ) // or inFile.good()
    {
        while (getline(inFile, mystring)) 
        {
            cout << mystring << endl;
        }
    }
    else
    {
        cout << "Could not open File\n";
    }
    return 0;
}

这一直对我有用,

while(!infile.eof) //until end of file
  {
    char tempCharArray[250];   
    infile.getline(tempCharArray,250);   //pushing the lines into Temporary Character Array
    std::string reqString(tempCharArray); //converting C-style string to std::string. this reqString can be edited as per your logic.
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM