【问题标题】:Int value is changing by itself after a for loopint 值在 for 循环后自行变化
【发布时间】:2018-02-14 20:21:53
【问题描述】:

在我的 CRA_Account.cpp 文件中,我的 socialInsuranceNumber 在

之后发生了变化
(j = 0; j <= max_name_length; j++) {
                given_name[j] = givenName[j];
            }

发生。 例如:如果我输入 123123123 作为我的 SIN,它将更改为 123123148。之前的 for 循环具有

for (j = 0; j <= max_name_length; j++) {
                family_name[j] = familyName[j];
            }

不会改变我的 socialInsuranceNumber 值。

我的代码是:

w3_in_lab.cpp

#include <iostream>
#include "CRA_Account.h"

using namespace std;
using namespace sict;

int main() {
    const int size = 1000;
    char familyName[size];
    char givenName[size];
    sict::CRA_Account myCRA;
    int sin;
    bool quit = false;
    if (sict::max_name_length + 1 > size) {
        cerr << "Increase size to value greater than " 
            << sict::max_name_length + 1 << endl;
        return 1;
    }

    cout << "Canada Revenue Agency Account App" << endl
         << "=================================" << endl << endl;
    cout << "Please enter your family name: ";
    cin >> familyName;
    cin.ignore();
    cout << "Please enter your given name: ";
    cin >> givenName;
    cin.ignore();

    do {
        cout << "Please enter your social insurance number (0 to quit): ";
        cin >> sin;
        cin.ignore();
        if (sin != 0)
        {
            myCRA.set(familyName, givenName, sin);
            if (myCRA.isEmpty()) {
                cout << "Invalid input! Try again." << endl;
            }
            else {
                quit = true;
            }
        }
        else {
            quit = true;
        }
    } while (!quit);
    cout << "----------------------------------------" << endl;
    cout << "Testing the display function" << endl;
    cout << "----------------------------------------" << endl;
    myCRA.display();
    cout << "----------------------------------------" << endl;

    return 0;
}

CRA_Account.cpp

#include <iostream>
#include "CRA_Account.h"
#include <cstring>

using namespace std;
using namespace sict;
    void CRA_Account::set(const char* familyName, const char* givenName, int sin) {
        int j;
        if (sin >= min_sin && sin <= max_sin) {
            socialInsuranceNumber = sin;
            for (j = 0; j <= max_name_length; j++) {
                family_name[j] = familyName[j];
            }
            for (j = 0; j <= max_name_length; j++) {
                given_name[j] = givenName[j];
            }
        }
        else {
            socialInsuranceNumber = 0;
        }
    }

    bool CRA_Account::isEmpty() const {
        bool empty = false;
        if (socialInsuranceNumber <= 0) {
            empty = true;
        }
        return empty;
    }
    void CRA_Account::display() const {

        if (isEmpty()) {
            cout << "Account object is empty!" << endl;
        }
        else {

            cout << "Family Name: " << family_name << endl;
            cout << "Given Name: " << given_name << endl;
            cout << "CRA Account: " << socialInsuranceNumber << endl;

        }
    }

CRA_Account.h

#ifndef CRA_ACCOUNT_H
#define CRA_ACCOUNT_H

namespace sict {
    static int max_name_length = 40;
    static int min_sin = 100000000;
    static int max_sin = 999999999;

    class CRA_Account {
    public:
    void set(const char* familyName, const char* givenName, int sin);
    bool isEmpty() const;
    void display() const;

    private:
        char family_name[40];
        char given_name[40];
        int socialInsuranceNumber = 0;

    };

}
#endif

【问题讨论】:

  • 使用字符串而不是字符数组。请提供minimal reproducible example
  • 这看起来有问题j &lt;= max_name_length
  • 你应该使用std::string而不是char array,如果你需要使用数组,那么使用strncpy()而不是循环。
  • Debugminimze to relevant code 在发布问题之前请!
  • 或者像“in Orbit”这样的名字

标签: c++ arrays loops for-loop int


【解决方案1】:

在 C++ 和 C 数组中,索引是从 0 开始的,这意味着索引在 [0,n-1] 范围内有效。常见的迭代模式是:

for( size_t i = 0; i < array_size; ++i )

有些人甚至更喜欢写作:

for( size_t i = 0; i != array_size; ++i )

所以你的循环:

for (j = 0; j <= max_name_length; j++) {

是错误的,因为它迭代范围 [0,n] (含)并通过访问具有错误索引的数组导致 UB。在您的情况下,您复制了socialInsuranceNumber 所在的部分内存。所以修复你的循环,问题就会消失。

注意:您应该使用std::string 而不是 char 数组,这不仅可以简化您的代码,还可以减少出错的可能性。如果你需要使用char数组,那么你应该使用标准C库中的strncpy()函数,而不是手动循环。

【讨论】:

  • 我们真的必须一遍又一遍地回答简单的错字(很好的扩展概念)问题吗?评论和近距离投票(或者甚至更好的欺骗锤)呢?
  • 如果你发现被骗我会删除我的答案,我发誓
  • 找到比The Definitive C++ Book Guide and List 更好的骗子可能太简单了 :-P ...但是关于我最初的评论:你妨碍了roomba(我真的不想再深入depth about that matter)。
  • @Andrew Sure strncpy() 需要另一个参数来指定目标缓冲区的最大大小。
猜你喜欢
  • 2018-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-29
  • 2013-05-11
  • 2015-02-05
  • 2018-04-07
  • 1970-01-01
相关资源
最近更新 更多