简体   繁体   中英

How to read a line using scanf in c++?

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

%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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM