【问题标题】:Retrieve all data via void function通过 void 函数检索所有数据
【发布时间】:2017-03-15 10:30:29
【问题描述】:

一直在努力寻找解决办法。我是 C++ 的新手,我创建了一个简单的程序来获取用户数据、验证和 cout 到屏幕。我想要做的是让一个函数使用指针来获取用户输入并显示给他们。这可能以前已经回答过,但我没有找到它。

到目前为止,我有以下代码

#include <iostream>

using namespace std;

void userData(int&);

int main(){
int a = 0;
int * kmpointer;   
int * dayspointer;

userData();

cout << "You ran " << userData(kmpointer) << endl;    
cout << "in " << userData(dayspointer) << "days!!" <<endl;

}

void userData(int& i){
cout << "Enter how Many Km's you ran:";

while (true)
{
    cin >> kmpointer;

    if ((cin) && (kmpointer >= 0) && (inputYear <= 100))
    break;

cin.clear();
cin.ignore( 100, '\n' );
cout << "That can't be right!\n";
cout << "Enter how Many Km's you ran:";
}

cout << "How many days in a row did you run?";
while (true)
{
    cin >> dayspointer;

    if ((cin) && (dayspointer >= 1) && (dayspointer <= 100))
    break;

cin.clear();
cin.ignore( 1000, '\n' );
cout << "Thats way to much!";
cout << "How many days in a row did you run? ";
}

}

【问题讨论】:

  • 您的问题是什么?您的代码充满错误,请尝试一一解决;-)
  • 抱歉 - 试图从函数中检索用户输入并使用指针将它们显示到屏幕上。我只是 C++ 的新手,并且正在慢慢地完成它。
  • userData 引用了一个int,所以发送一个int 就像userData(a),除非我怀疑你想发送所有三个整数。不需要是指针。

标签: c++ function parameter-passing cin


【解决方案1】:

IMO,您应该从阅读 C++ 开始。您缺少一些基本概念,并且尝试了对您的级别而言过于复杂的练习。

1 函数未声明/定义。

2 userData 声明接受参数,但不使用。

3 您面临的问题可能与我们所说的scope 有关:变量仅在其范围内存在且可见(通常由{} 括起来。

在您的情况下,kmpointerdayspointer 仅在 main 函数中可见,因此您不能在 userData 中使用它们。

为了解决这个问题,我建议您将这些变量作为参数传递给userData

4 指针、引用、值:它们是不同的。您将用户输入保存为指针地址,这确实是有问题的。

常规

一般来说,您的代码充满了错误。尝试Hello world! 并从那里逐步继续。

【讨论】:

  • 此外:“cin 不会像您期望的那样使用指针”,甚至“不要在 C++ 中使用原始指针,它们仅在非常特殊的情况下有用”和“学习关于参考”
【解决方案2】:

专注于您提出的具体问题(尽管观察到您的代码中还有其他问题),不要使用指针,使用引用。

在我们开始之前

cout << "You ran " << userData(kmpointer) << endl;

不会编译,因为您知道 userData 是一个 void 函数,因此将 &lt;&lt; 应用于它没有任何意义。它是无效的,所以没有什么可以流式传输的。

您说您想将参数传递给函数并让它们被更改,所以这样做。然后显示变量。 (不是void 函数调用的“结果”)。

正确获取用户输入是一个单独的问题,之前已经回答过。

#include <iostream>

using namespace std;

void userData(int& i, int& j, int& k);

int main() {
    int a = 0;
    int kmpointer;
    int dayspointer;

    //Here we call our function, ONCE
    userData(a, kmpointer, dayspointer);

    //Here we display what values we now have
    //after calling the function, ONCE
    cout << "You ran " << kmpointer << endl;
    cout << "in " << dayspointer << " days!!" << endl;

}

//simplified to demonstrate changes to the reference parameters
void userData(int& i, int& j, int& k) {
    //Here we have three parameters which we refer to as i, j and k
    // They may have different names ousdie in the calling code
    //  but this function (scope) neither knows nor cares
    j = 42;
    k = 101;
}

【讨论】:

    猜你喜欢
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 2023-03-25
    相关资源
    最近更新 更多