1

首先,这是一个“家庭作业”问题,因此向量库和字符串库是不受限制的。我正在尝试了解 C++ 的基础知识。

我对这段代码的意图是制作和使用一个字符串数组。换句话说,单词列表。

当我运行这段代码时,我得到了一堆废话。

如果有更好的方法来制作 c++ 中的单词列表,我很想听听。

const int cart_length = 50;
const int word_length = 50;

int main()
{

char cart_of_names[cart_length][word_length]; 
float cart_of_costs[cart_length];

char name[word_length];
cout << "enter the name of the first item: ";
cin >> name;
for(int i=0; i<word_length; i++)
{
    cart_of_names[0][i] = name[i];
}
cout << endl;
cout << "that is: ";
for(int x=0; x<word_length; x++)
{   

        cout << cart_of_names[0][x];
}
cout << endl;

return 0;
}
4

9 回答 9

4

如果输入的字符串不是 50 个字符长 ( cart_length),则名称中的有效字符将少于 50 个。你应该if(cart_of_names[0][x]==0) break;在你的第二个循环中有一个。

于 2009-10-05T16:34:15.180 回答
2

我不完全明白你在找什么。以下代码将帮助您阅读和打印 50 个单词的列表。希望这会对你有所帮助。

const int cart_length = 50;
const int word_length = 50;

int main()
{

    char cart_of_names[cart_length][word_length]; 
    float cart_of_costs[cart_length];

    for(int i=0; i<cart_length; i++)
    {
        cout << "enter the name of the " << i + 1 << "th item: ";

        cin >> cart_of_names[i];
    }

    cout << "that is: ";

    for(int x=0; x < cart_length; x++)
    {       
        cout << cart_of_names[x] << endl;
    }

    return 0;
}
于 2009-10-05T16:49:06.507 回答
2

查看 STLSoft 的fixed_array_2d(它是高阶兄弟)。在 Matthew Wilson 的Imperfect C++中有详细讨论如何实现它们以获得最大性能。

于 2009-10-05T21:26:03.687 回答
0

“如果有更好的方法来制作 c++ 中的单词列表,我很想听听。”

包括#include <string>和使用std::string. 我认为该std::string类型是 C++ 规范的一部分。

#include <iostream>
#include <string>

int main(void) {
  std::string list[7];

  list[0] = "In C++";
  list[1] = "you can use";
  list[2] = "the `std::string` type.";
  list[3] = "It removes";
  list[4] = "many of the problems";
  list[5] = "introduced by";
  list[6] = "C-style strings.";

  for (int k=0; k<7; k++) std::cout << list[k] << ' ';
  std::cout << '\n';
  return 0;
}
于 2009-10-05T20:23:19.007 回答
0

如果您使用 strcpy() 而不是 cart_of_names[0][i] = name[i];

它可能会更好,但我只是看着所有这些代码就感到畏缩。

于 2009-10-05T16:32:50.610 回答
0

除非您被禁止使用 STL(这只是意思),否则请使用std::list<std::string>. www.cplusplus.com 有这些类的详细描述和示例。

否则,您会遇到 char 数组数组:在这种情况下,请为大量缓冲区溢出错误做好准备。在上面的网站上查看 char[] 管理功能(strncpy()等等),它们会让你的生活更轻松一些(但不是很多)。

于 2009-10-05T16:34:19.267 回答
0

如果您不能使用 std::string,请至少查看 C 中的 strncpy() 之类的函数以进行名称复制。此外,您忘记了 c 风格的字符串是空终止的。

于 2009-10-05T16:31:01.303 回答
0

在 C 中,我发现概念化您正在尝试做的事情的最佳方法是使用 char* 数组。同样的效果,但如果你开始使用它,我相信你会发现它对大脑更容易。

于 2009-10-05T16:49:26.070 回答
0

它看起来离我很近。C 中的字符串以空字符结尾,这意味着字符串的结尾由空字符指示。从某种意义上说,C 中的字符串实际上只是一个字节数组。

当你这样做时:

cout << "enter the name of the first item: ";
cin >> name;

如果我输入字符串“Book”,在内存中它看起来像这样:

|0|1|2|3|4|5..49|
|B|o|o|k|0|*HERE BE DRAGONS*

好吧,实际上它将包含对应于这些字母的ASCII 值,但出于我们的目的,它包含这些字母。here be dragons一些你没有初始化的内存,所以它包含你的平台设置的任何垃圾。

因此,当您复制字符串时,您需要0在字符串末尾查找该字节。

for(int i=0; name[i]!=0; i++)
{
    cart_of_names[0][i] = name[i];
}

然后当你输出它时,你实际上不需要一次做一个字符。你可以这样做cout<<cart_of_names[0]cout由于终止空字符,知道字符串在哪里结束。

于 2009-10-05T16:50:12.123 回答