Hi guys.
Writing to a file I found this issue.
I want to use fscanf
and i go:
1 2
string name = "Luca";
fscanf( pFile, "%s", name );
This does NOT work because 'name' should be an array of characters and NOT a std::string in order to be accepted as argument.
How can I do?
Can anybody point me in the right direction?
I really need to pass a string to a file. Do you guys know of another function similar to fprintf that accepts std::string ? thanks
I don't understand why you would use fscanf with a std::string. Why not just use an ifstream and the usual C++ formatted input.
However, to answer your question, you could use a character array instead of a string with fscanf. Make sure the array is big enough to hold the string being read in.
Well, are you familiar with using cin to get input? That is an example of an input stream, which gets its data from the keyboard. An ifstream can do more or less the same thing, but takes its input from a file instead.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main()
{
ifstream fin("input.txt");
string word, line;
fin >> word;
getline(fin, line);
cout << "word = " << word << endl;
cout << "line = " << line << endl;
return 0;
}
while i agree with above, to answer your first question: the string class has a method called c_str() which returns a char* of the string it currently holds
kind of. a) i wouldnt make it an int array, because it returns a char*. if you need to convert to int i would use stringstream b)and this is just preference i dont know if there is a real danger to doing it char array[] = name.c_str(), but i would do char *array = name.c_str()
Could you please show me how to do what I have been doing with "fscanf" and "fseek" ?
I don't know what you were doing, I don't think you made that clear.
But rather than try to convert your old code into new code, it might be better if you just describe what it is you want the program to do.
Don't worry!! I am doing great ( lol )
I'll send you my code once it's done as I am sure you'd have many things to say about the way I code and I can't wait to hear them as I don't want to pick up bad coding habits from the start