如何在c++中使用scanf读取线条

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

本文关键字:scanf 读取 c++      更新时间:2024-09-23

我正在尝试使用"scanf";读取字符串行:";它不工作吗";,但我不知道是否有可能在这个特定的例子中实现它。

#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("%dn%lfn%s", number+i, doub+d,s+longText); //Print all the values, but not printing s+longText
}

显示代码的图像

printf/scanf家族中的%s代表char数组,而不是std::string。如果您想获得线路,请使用std::getline。如果您想为stdio函数使用std::string缓冲区,请使用std::string::data函数,但我不建议这样做,因为缓冲区可能会溢出,尤其是对于像get line这样的函数。