fscanf in C++

Hi
I want to use fscanf to get data from a file "ecrire.txt":
30
lalal

50
lllll

99
kkkk

Here is my code in C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  void reading(char name[]){
    //2)
    //similar in c
    int a;
    char s[20];
    FILE *file=fopen (name,"r");
    if(file!=NULL){
        while(!feof(file)){
            fscanf(file,"%d",&a);
            printf("%d\n",a);
            fscanf(file,"%s",s);
            printf("%s\n",s);
            fscanf(file,"%s",s);
            printf("\n");
        }
    }
    fclose(file);
}


My codeblocks shows everytime :
30
lalal

30
lllll

30
kkkk


I'd like to know why the a does't change?

Thanks for any help you can give.



I see no aspect of C++ in your code.

But anyway, what are you expecting line 13 to do? *scanf functions skip whitespace.
Remove your third fscanf.

PS: Here is your code in C++.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>   
#include <string> 

void reading(const std::string& filename)
{
    std::ifstream ifs(filename);
    int num;
    std::string str;
    while (ifs >> num >> str)
    {
        std::cout << num << "\n"
                  << str << "\n\n";         
    }
}

int main()
{
    reading("test.txt");
}
Last edited on
This is not c++?
I've studied c++ for 3 weeks,
I've thought that we could use fscanf in c++ .....

Anyway , How can I get data from my file in this forme?
yes and no :)
c++ absorbed 95% or so of the C language and most of it works fine in "c++" as in you can use it and it will compile and function. But its still C, not C++. So technically its "c++" because the compilers will take it in a .cpp file using a c++ compiler and linker, but "professionally" its not c++ as it is preferred to use the C++ (not found in C) types and functions for anything redundant across the two languages.

you can use them, but its highly not recommended.

Ganado showed you the c++ version. It does get the data from the file. You may need to add to it if you want to store the file data in something... all it does is read it in and print it out so far.
heros666, yeah I meant what jonnin said.

You didn't answer my question (although it was somewhat rhetoric).
I told you how to fix your problem: Remove the third fscanf statement, it doesn't make any sense to exist right there. You can ignore my code example if you wish; for your purposes, it's unrelated.
Last edited on
Ganado (1892)
Non, Ive not ignored your code, your code was not showed on my phone,
Ive not seen it.
Now l am on my compute, it is showed,
Yes, thanks a lot for your code.
And thanks for jonnîn's explanation.
Topic archived. No new replies allowed.