【问题标题】:Identifier "friends_name" is undefined & the Identifier "input " is undefined? C++标识符“friends_name”未定义且标识符“输入”未定义? C++
【发布时间】:2018-04-02 21:17:36
【问题描述】:

我正在尝试提示用户输入他或她的名字。 我写了“hello,first_name”,其中 first_name 是用户输入的名称。 然后我修改代码如下:将提示更改为“输入您要写信的人的姓名”并将输出更改为“Hello,first_name”,然后您喜欢您现在的生活吗(y / n)?"; 这是在我写一个 if 语句之前,让用户决定要执行什么代码,但是我给定的“条件”中的输入不起作用,因为尽管我将它们分配给'y'和'但它未定义n'。 长话短说我不完全了解如何定义 first_name 和输入,我试图让用户输入这些值以分配给这些变量。 The Error list

 #include "stdafx.h"
 #include "iostream"
 #include"string"
 using namespace std;

 int main()
     {
string first_name;
cout << " Please enter your first name (followed by 'enter'):\n";
cin >> first_name;
    cout << "Hello," << first_name << " do you like where you are right now in life (y/n)?:\n";
    cin >> first_name;
    if (input =='y') {
        cout << "what do you like about it over,the people?(y/n)";//?:\n"

    }
    else if (input == 'n') {
        cout << " what do you hate about it,the expenses?(y/n)"//?:\n"
    }
    else cout << "invalid choice";
    cout << " what was your friends name again ?" << endl;
    string = friends_name;
    cin >> friends_name;
}
return 0;
     }
   }

【问题讨论】:

  • 你在代码的什么地方定义了friends_name?也许string = friends_name 中的= 是错字?查看您声明 first_name 的行。
  • 这是我的主要问题,我不明白我是如何声明first_name 的,当id 喜欢用户输入first_name 的值时。是的,这是一种类型,我的意思是数据类型字符串后跟friends_name;
  • @ThomasMatthews Matthews,friends_name 是怎么写的,变量在哪里声明并且可以用于用户输入?
  • @ThomasMatthews,代码的最后一部分有问题,else cout
  • 当我尝试编译您的示例时,我收到错误,因为 friends_name 未定义。您的意思是在没有'=' 的情况下使用string friends_name;

标签: c++ visual-studio input undefined


【解决方案1】:

在程序的第 12 行中,您似乎使用了变量 first_name 而不是输入。将“first_name”替换为“input”。 例如:

cin>>input

同样如 cmets 中所述,请确保声明您使用的所有变量

例如:

string first_name;
string input;
string friends_name;

编辑后的工作代码如下:

 #include "stdafx.h"
 #include "iostream"
 #include"string"
 using namespace std;

int main(){
 string first_name;
 string friends_name;
 string input;
 cout << " Please enter your first name (followed by 'enter'):\n";
 cin >> first_name;
 cout << "Hello," << first_name << " do you like where you are right now in life (y/n)?:\n";
 cin >> input;
 if (input =="y")
     cout << "what do you like about it over,the people?(y/n)";//?:\n"
 else if (input == "n")
    cout << " what do you hate about it,the expenses?(y/n)";//?:\n"
 else cout << "invalid choice";
 cout << " what was your friends name again ?" << endl;
 cin >> friends_name;
 return 0;
 }

【讨论】:

  • OP 还需要声明变量input
  • 你如何声明操作(我假设操作是指操作符)现在我得到这个 // 没有操作符 "==" 匹配这些操作数。这是什么意思,@ThomasMatthews?
  • OP 是原始海报的缩写。其次,在您的代码中,左大括号和右大括号相距甚远(最后在 main 中多了两个,return 0 之前的一个应该移到 return 0 之后)。
  • 另外,您的代码中存在语法错误(“input=='n'”的 cout 行中缺少分号)。确保检查这些
  • @AnkitPatnaik,你把一切都清理干净了。
猜你喜欢
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多