首页 > 解决方案 > 为什么我的代码不返回 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.

标签: c++scanf

解决方案


您的第一个程序具有未定义的行为。

scanfprintf期望%s指向 的指针char,而不是指向 的指针std::string。它们是 C 库函数,因此对 C++ 类型(例如std::string. 您需要提供正确的类型作为格式说明符的参数。如果你不这样做,你的程序有未定义的行为。

因此,在第一个代码块中,您需要替换

string name[15];

char name[15];

请注意,这仍然是不安全的,因为如果用户输入长度超过 14 个字符的字符串,您将越界访问数组,再次导致该输入出现未定义的行为。

此外,在编译器中启用警告,例如使用编译器标志

-Wall -Wextra

在 GCC 和 Clang 中。然后编译器很可能会警告您错误的参数类型。

此外,在第一个程序中替换#include<iostream>为。并且由标准库头文件提供。不保证包括它们。同样第二个方案需要额外的,因为也不能保证提供。#include<cstdio>scanfprintf<cstdio><iostream>#include<string><iostream>std::string


推荐阅读