简体   繁体   English

变量已自动分配

[英]Variable is getting assigned automatically

I was making a project that gets students' names, roll numbers & marks and returns percentage or grade according to need of user. 我当时正在做一个能够获取学生姓名,卷号和分数并根据用户需要返回百分比或等级的项目。 I made a function using for loop to assign details(name, etc.) to variable but during change of for loop's argument, program was assigning ""(null) to the first variable in execution part. 我做了一个使用for循环的函数,将详细信息(名称等)分配给变量,但是在更改for循环的参数期间,程序将“”(空)分配给执行部分中的第一个变量。 Am I missing any code here? 我在这里错过任何代码吗?

#include <iostream>
#include <stdio.h>

using namespace std;

class Data 
{
    public: 
    int Rno[3], phy[3], mat[3], chem[3];
    char name[3][100];

    void getInfo()
    {
        for(int i = 0; i < 3; i++)
        {
            cout << "Enter your name: ";
            gets(name[i]);

            cout << "Enter your Roll number: ";
            cin >> Rno[i];

            cout << "Enter your Physics marks: ";
            cin >> phy[i];

            cout << "Enter your Maths marks: ";
            cin >> mat[i];

            cout << "Enter your Chemistry marks: ";
            cin >> chem[i];
       }
    };
};

int main()
{
    Data d;

    d.getInfo();
    puts(d.name[1]);
}

Problem is with not flushing cout . 问题在于没有冲洗cout In your case inside the loop cout must be flushed before calling gets . 在你的情况下,循环中cout调用之前必须冲洗gets

cout << "Enter your name: "<<endl;  // This cout should be flushed properly **with** new line character
gets(name[i]);

From @ProXicT comment 来自@ProXicT的评论

cout << "Enter your name: "<<flush;  // This cout should be flushed properly **without** new line character
    gets(name[i]);

First an explanation. 首先说明一下。 Then some options to address the problem. 然后是一些解决该问题的方法。

The problem is that you are mixing line-oriented input ( gets() ) with formatted input ( cin >> .... ) on the same input device/stream. 问题是您在同一输入设备/流上混合了面向行的输入( gets() )和格式化的输入( cin >> .... )。

Such functions treat whitespace - particularly newlines - differently. 此类函数对空格(尤其是换行符)的处理方式不同。 And, because of that, you can get unexpected interactions. 而且,因此,您可以获得意外的交互。 In this case, cin >> chem[i] will read an integral value, stop when it encounters a newline, leave the newline character waiting to be read. 在这种情况下, cin >> chem[i]将读取一个整数值,在遇到换行符时停止,让换行符等待读取。 Then gets() - in the next iteration of the loop - will encounter the newline, and return immediately (hence the "null", to use your description). 然后, gets() (在循环的下一个迭代中)将遇到换行符,并立即返回(因此,使用您的描述为“ null”)。

OK; 好; that's the explanation. 这就是解释。 What to do about it? 怎么办呢?

The solution is not to mix such styles of input. 解决方案是不要混合使用这种样式的输入。 One option consistently use line oriented input to read EVERYTHING as a string, and then separately parse the string. 一个选项始终使用面向行的输入以字符串形式读取所有内容,然后分别解析该字符串。

Some people will suggest approaches that involve discarding (or "flushing") the offending newlines. 有人会提出一些方法,包括丢弃(或“刷新”)令人讨厌的换行符。 That approach doesn't work well if your input is complex (eg lots of different statements reading from the same stream in different ways) because it is necessary to ensure EVERY stray newline is discarded. 如果您的输入很复杂(例如,许多不同的语句以不同的方式从同一流中读取),则该方法效果不佳,因为有必要确保丢弃所有流浪换行符。 It is also error-prone - you can unintentionally discard input your program needs to read. 它也容易出错-您可能无意中放弃了程序需要读取的输入。

Also avoid using gets() like the plague. 还要避免像瘟疫一样使用gets() It has been removed from recent C standards for a reason - it is inherently unsafe. 由于某种原因,它已从最新的C标准中删除-本质上是不安全的。

There are various ways using C++ streams (like cin ) to safely read strings and other types. 使用C ++流(例如cin )可以通过多种方式安全地读取字符串和其他类型。 For example, if some_str is of type std::string , then std::getline(std::cin, some_str) can be used to read a complete line of input. 例如,如果some_str类型为std::string ,则可以使用std::getline(std::cin, some_str)读取完整的输入行。 std::getline() also has the advantage that it can read a string of arbitrary size. std::getline()还具有可以读取任意大小的字符串的优点。 But, still, avoid using std::getline(cin, some_str) and streaming input ( cin >> ... ) on the same stream - because they STILL handle newlines differently. 但是,仍然避免在同一流上使用std::getline(cin, some_str)和流输入( cin >> ... )-因为它们仍然以不同的方式处理换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM