0

I'm trying to use "scanf" to read a string line: "is it not working", but I don't know if it's even possible to implement it in this particular example.

    #include <iostream>
    #include <iomanip>
    #include <limits>
    #include <string>

    using namespace std;

    int main() {
        int i = 4;
        double d = 4.0;
        string s = "Just an example of, why ";
        int number;
        double doub;
        string longText;
 
        scanf("%d %lf %s", &number, &doub, &longText); //Read a line ex ("is it not working")    
        printf("%d\n%lf\n%s", number+i, doub+d,s+longText); //Print all the values, but not printing s+longText

}

Image showing the code

  • 1
    Does this answer your question? [Reading a line using scanf() not good?](https://stackoverflow.com/questions/17294809/reading-a-line-using-scanf-not-good) – Aykhan Hagverdili Nov 11 '20 at 05:50
  • 1
    [Turn on your compiler warnings](https://gcc.godbolt.org/z/bbPqKE) – chris Nov 11 '20 at 05:51
  • 2
    And ALWAYS check the return code to make sure you got all of the inputs you wanted. Users are vicious fiends. Those that aren't actively trying to break your program are going to break it by accident. Never trust them. – user4581301 Nov 11 '20 at 06:02
  • If your input is "is it not working", how do you think the program will extract numbers from it? – R Sahu Nov 11 '20 at 06:09
  • Read this carefully, and pay attention to the format specifiers: https://en.cppreference.com/w/cpp/io/c/fscanf - not all of those that you use are correct as @chris points out – Paul Floyd Nov 11 '20 at 06:53

1 Answers1

0

%s in printf/scanf family stands for char array, not std::string. If you want to get line, use std::getline. If you want to use std::string buffer for stdio functions, use std::string::data function, but I wouldn't suggest that as buffer-overflow is likely, especially for something like get-line.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93