c++ - 为什么我的代码不返回 0?我正在使用 scanf() 而不是 cin
问题描述
我想确保我了解如何使用scanf()
,但我不明白为什么我的代码没有返回 0。我知道scanf()
在循环等方面有它自己的问题,但它让我感到困惑如何简单的事情显示字符串不会返回 0。
我的代码可能有什么问题吗?
我输入和显示名称的简单代码如下:
#include <iostream>
using namespace std;
int main() {
string name[15];
printf("Please type your name: ");
scanf("%s", &name);
printf("Your name is %s", name);
return 0;
}
输出将是:
Your name is hello
Process returned -1073740940 (0xC0000374) execution time : 4.356 s
Press any key to continue.
而如果我使用cin
/cout
而不是scanf()
/ printf()
,
#include <iostream>
using namespace std;
int main(){
string name;
cout << "Please type your name: ";
cin >> name;
cout << "Your name is: " << name;
return 0;
}
输出:
Please type your name: hello
Your name is: hello
Process returned 0 (0x0) execution time : 3.794 s
Press any key to continue.
解决方案
您的第一个程序具有未定义的行为。
scanf
并printf
期望%s
指向 的指针char
,而不是指向 的指针std::string
。它们是 C 库函数,因此对 C++ 类型(例如std::string
. 您需要提供正确的类型作为格式说明符的参数。如果你不这样做,你的程序有未定义的行为。
因此,在第一个代码块中,您需要替换
string name[15];
和
char name[15];
请注意,这仍然是不安全的,因为如果用户输入长度超过 14 个字符的字符串,您将越界访问数组,再次导致该输入出现未定义的行为。
此外,在编译器中启用警告,例如使用编译器标志
-Wall -Wextra
在 GCC 和 Clang 中。然后编译器很可能会警告您错误的参数类型。
此外,在第一个程序中替换#include<iostream>
为。并且由标准库头文件提供。不保证包括它们。同样第二个方案需要额外的,因为也不能保证提供。#include<cstdio>
scanf
printf
<cstdio>
<iostream>
#include<string>
<iostream>
std::string
推荐阅读
- javascript - 给定数字数组的可能三角形数问题
- vba - VBA:Excel宏在调试中正确执行,但在执行时不运行子
- javascript - 在 React Native 中使用 Google Contacts Api
- jenkins - 使用 Jenkins 作业存储和查询键/值 (UUID)
- angularjs - 查看 mongodb 集合时,MEAN 堆栈未加载页面
- c# - C# chrome tab 获取索引
- python - 在 Flask 中将 GET 方法转换为 POST 方法
- javascript - 如何使用 javascript 搜索 PDF 文件标题和/或内容。
- c++ - 内存增加和字符串流?
- javascript - 将 pym.js 与 Github 页面一起使用将不起作用