c++ scanf 怎么读入string类型变量
时间: 2023-08-07 16:10:46 浏览: 92
在C++中,`scanf`函数不能直接读取`std::string`类型的变量,因为`scanf`是C语言的输入函数,无法处理C++的`std::string`。
如果你想读取一个字符串变量,可以使用`std::cin`来实现。`std::cin`是C++中标准输入流对象,用于从控制台读取输入。
以下是使用`std::cin`读取字符串的示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str;
std::cout << "Enter a string: ";
std::cin >> str;
std::cout << "You entered: " << str << std::endl;
return 0;
}
```
在上述示例中,我们使用`std::cin`来读取用户输入的字符串,并将其存储在名为`str`的`std::string`变量中。然后,我们通过`std::cout`将输入的字符串打印出来。
请注意,使用`std::cin`读取字符串时,它会以空白字符(例如空格、制表符、换行符)为分隔符,只读取第一个单词作为字符串。如果你需要读取整个带有空格的字符串,可以使用`std::getline(std::cin, str)`函数来读取。
相关问题
用scanf读入string
scanf函数可以用来读取字符串,但是它无法像直接输入整数那样方便地使用scanf()函数输入string变量。因为string并非是C的原生类型。但是我们可以通过预先分配空间来实现scanf输入string类型的数据。下面是两种方法:
方法一:
```c++
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
int main() {
string a;
a.resize(2); // 需要预先分配空间
scanf("%s", &a[0]);
cout << a;
return 0;
}
```
方法二:
```c++
#include<iostream>
#include<string>
using namespace std;
int main() {
string str_scanf;
printf("str_scanf:");
scanf("%s",str_scanf.c_str()); // c方法输入
printf("%s\n", str_scanf.c_str()); // 输出
return 0;
}
```
不用string
好的,下面是不使用 `string` 类型的 C++ 代码实现:
```cpp
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
// 获取输入的日期
int birth_year, birth_month, birth_day, today_year, today_month, today_day;
scanf("%d-%d-%d", &birth_year, &birth_month, &birth_day);
scanf("%d-%d-%d", &today_year, &today_month, &today_day);
// 根据题目要求计算天数
int days = (today_year - birth_year) * 365 + (today_month - birth_month) * 30 + (today_day - birth_day);
// 输出结果
cout << days << endl;
return 0;
}
```
这个实现方式直接使用 `scanf` 函数来读取输入的日期,不需要使用 `string` 类型。同时,由于输入的日期中间是由 `-` 分隔的,所以可以直接使用该符号来进行读取,无需再使用 `char` 类型的变量。