I want to read the string from file input into a std::string variable.
I declare a FILE pointer to open file:
FILE *f = fopen("IN.txt","r");
And then, I read using fscanf() function:
std::string tempStr;fscanf(f,"%s",tempStr); //Compile Error//fscanf(f,"%s",&tempStr);//Runtime Error
So, I have 2 question:
1. Is it possible to fix the problem above (Still use FILE *f and fscanf() function)?
2. I'm a C programmer, new to C++. How to solve this problem with the different way?
Here is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
string cities[100];
FILE * f = fopen("IN.txt", "r");
fscanf(f,"%d",&n);
for (int i=0; i<n;i++)
{
string tempStr;
fscanf(f,"%s",tempStr);
cities[i] = tempStr;
}
return 0;
}
And the input file (first line is numbers of line):
8
Vancouver
Yellowknife
Edmonton
Calgary
Winnipeg
Toronto
Montreal
Halifax
Aucun commentaire:
Enregistrer un commentaire