如何在 C++ 中使用 scanf 读取一行?
How to read a line using scanf in c++?
我正在尝试使用“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("%d\n%lf\n%s", number+i, doub+d,s+longText); //Print all the values, but not printing s+longText
}
Image showing the code
printf
/scanf
家族中的%s
代表字符数组,而不是std::string
。如果要获取行,请使用 std::getline
。如果你想为 stdio 函数使用 std::string
缓冲区,请使用 std::string::data
函数,但我不建议这样做,因为缓冲区溢出是可能的,特别是对于像 get-line 这样的东西。
我正在尝试使用“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("%d\n%lf\n%s", number+i, doub+d,s+longText); //Print all the values, but not printing s+longText
}
Image showing the code
printf
/scanf
家族中的%s
代表字符数组,而不是std::string
。如果要获取行,请使用 std::getline
。如果你想为 stdio 函数使用 std::string
缓冲区,请使用 std::string::data
函数,但我不建议这样做,因为缓冲区溢出是可能的,特别是对于像 get-line 这样的东西。