0

I am trying to take array of string as a input but its giving run time error

    #include<iostream>
    #include<cstdio>
    #include<string>
    using namespace std;

    int main()
    {
        string str[500];
        int n;
        cin>>n;
        for(int i=0;i<n;i++)
            scanf("%s",&str[i]); \\works fine with cin but gives error using scanf
        return 0;
    }

Process terminated with status -1073741510 (0 minute(s), 10 second(s))

works fine with cin but give error if i use scanf

Can some one tell me why its giving such error

what does that error mean and why doesn't it gives error while using cin

I am using code blocks 13.12

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
Rajnish
  • 419
  • 6
  • 21
  • [Same reason as `printf`](http://stackoverflow.com/questions/10865957/c-printf-with-stdstring/10865967#10865967) – chris Apr 04 '15 at 17:40
  • and whats the reason?? – Rajnish Apr 04 '15 at 17:41
  • 1
    `scanf` is a C function, and has no idea about C++ classes and objects like, for example, `std::string`. – Some programmer dude Apr 04 '15 at 17:41
  • @rajnish, > [`scanf`] has no option for std::string, only a C-style string. Using something else in place of what it expects definitely won't give you the results you want. It's actually undefined behaviour, so anything at all could happen. – chris Apr 04 '15 at 17:42
  • @chris can u please elaborate it a bit more, i got that its like undefined for C-style string but how does that exactly work, i mean to say i have included cstdio libraries so compiler would get its reference from there, so i am a bit confused how it works in the background, like y its undefined? – Rajnish Apr 04 '15 at 17:47
  • @rajnish, `scanf` supports a limited set of types. `std::string` is obviously not on that list because `std::string` is a C++ type and `scanf` is a C function. – chris Apr 04 '15 at 17:55

3 Answers3

0

string is a C++ type, you should use C++ I/Os thus cin and cout. If you really want to use C I/Os you can access c_str method to get the C char * behind the string.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
  • Not `c_str()` because that gives a `const char *`. You need to resize it so that it's big enough to hold the string without modifying the null character at the end and then use something like `&str[i][0]`. This is only guaranteed to work in C++11, too. – chris Apr 04 '15 at 17:45
0

scanf() is meant to be used with C-style strings(aka char * or char[]), it should be

char myString[101];
char* myOtherString = (char*)malloc(101);
scanf("%100s", myString);
scanf("%100s", myOtherString);
free(myOtherString);

no reason to use this over std::string.

Alex Díaz
  • 2,303
  • 15
  • 24
0

You are using C++ to take advantage of cin The header file avoids the use of non null pointers and char arrays

cin>> has operator overload and users the modern string class

user4749532
  • 11
  • 1
  • 3