【问题标题】:How to store the string data in string 2D array in C++如何在 C++ 中将字符串数据存储在字符串二维数组中
【发布时间】:2017-09-06 02:58:01
【问题描述】:

我想将数据存储在二维数组 t[0][0] 的第一个索引处的第一个元素中! 我写了这段代码:

int main()
{
    string input;
    cout << "Enter string of code:\n";
    cin >> input;
    queue < string > m;
    string t[100][3];
    while (input != "^")
    {
        int i = 0;

        t[i][0] = input;
        m.push(t[i][0]);
        if (input == " ")
        {
            t[i + 1][0];
            break;
        }

        cin >> input;
        i++;

    }
    int c = 1;
    while (!m.empty())
    {
        int i = 0;
        t[i][0] = m.front();
        string temp;
        temp = t[i][0];
        t[i][1] = check(temp);
        //cout <<c<<" "<<t[i][0]<<" Is: " << t[i][1] << endl;
        c++;
        m.pop();
        i++;
    }
    cout << endl;

    cout << c << " " << t[0][0] << " Is: " << t[0][1] << endl;

    system("Pause");
    return 0;
}

我对这个说法有疑问

cout

这不会打印数组中的值!

【问题讨论】:

  • 你应该在while循环上方声明int i
  • @jhnnslschnr 谢谢你的帮助

标签: c++ string loops multidimensional-array


【解决方案1】:

在while循环上方声明并初始化i,像这样:

int i = 0;
while (!m.empty())
{
    t[i][0] = m.front();
    ...

让我解释一下(在你的代码中)发生了什么:

while (!m.empty())
{
    int i = 0;
    t[i][0] = m.front();
    string temp;
    temp = t[i][0];
    t[i][1] = check(temp);
    //cout <<c<<" "<<t[i][0]<<" Is: " << t[i][1] << endl;
    c++;
    m.pop();
    i++;
}

每次进入循环体时,都会声明一个名为i 的变量并将其初始化为0。i 的范围是循环体。

您在循环结束时增加i,但一旦循环再次运行,i 将再次被初始化为 0(您也重新声明它)。因此,如果我们在第二个循环中,您可能希望 i 的值为 1,但因为您每次进入循环时都初始化为 0,所以它总是的值为0,因为你正在执行循环体。


此外,这一行:

t[i + 1][0];

应该发出这样的警告:

main.cpp:22:23: warning: expression result unused [-Wunused-value]
            t[i + 1][0];
            ~~~~~~~~ ~^

我是这样编译你的代码得到的:

g++ -Wall main.cpp

标志墙启用所有警告的地方,很酷,把它变成你的朋友。

这很有帮助,就像现在发生的那样,因为该行不会对您的代码产生任何影响。


PS:当然,我不知道你代码中的check() 是什么,所以我只能说这些了。

【讨论】:

  • 非常感谢,它解决了我在使用这段代码时遇到的所有问题,我无法相信我花了多少时间来解决这个问题,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-20
  • 1970-01-01
  • 1970-01-01
  • 2015-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多