简体   繁体   中英

how to create a string from a txt file

I am attempting to take a txt file and create a string from it but I cannot figure out how to make it work.

I have tried to use the getline string function but it does not create a proper string in the way I have used it.

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

while (getline(inFile, mystring)) {

    cout << mystring << endl;
}

The end goal of my program is to read a.txt file line by line and edit each line so it is 100 char wide. This first part seems to be the only place where I am having an issue at the moment.

This can be due to the stream object could not find or open the file. Try checking if the inFile is good or valid.

#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;
}

This always worked for me,

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.
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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