Reputation: 33
I use VS2010 in windows 7 to write C++ mfc program. I want to read a txt file by line and pass it to the string array.
I have tried the testByLine function but it says name "fstream" is unidentified.Also, "ios::in" seems incorrect in my windows 7 but I do not know how to correct it.
#include "stdafx.h"
#include <fstream>
std::string Value_2[5];
void testByLine()
{
char buffer[256];
fstream outFile;
outFile.open("result.txt", ios::in);
int i = 0;
while (!outFile.eof()) {
outFile.getline(buffer, 128, '\n');
Value_2[i] = buffer;
i += 1;
}
outFile.close();
}
I expected every line in the txt being passed to each element of string array Value_2.
Upvotes: 1
Views: 48
Reputation: 368
You can do something like this.
#include <fstream>
#include <iostream>
#include <string>
int main(){
std::string read;
std::string arr[5];
std::ifstream outFile;
outFile.open("test.txt");
int count = 0;
//reading line by line
while(getline(outFile, read)){
//add to arr
arr[count] = read;
count++;
}
outFile.close();
//c++ 11
// for(std::string str : arr) std::cout << str << "\n";
for(int i = 0; i < 5; i++){
std::cout << arr[i] << "\n";
}
return 0;
}
Upvotes: 1