为什么我的代码不返回0?我使用的是scanf()而不是cin

问题描述 投票:0回答:2

我想确保我了解如何使用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(),但我不明白为什么我的代码没有返回0。我了解到scanf()在循环等方面有其自身的问题,但是这让我感到迷惑...

c++ scanf
2个回答
1
投票

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


-1
投票
    #include<iostream>
© www.soinside.com 2019 - 2024. All rights reserved.