【问题标题】:C++ Displaying a string (with blank spaces) into a two dimensional array?C ++将字符串(带空格)显示为二维数组?
【发布时间】:2017-03-27 12:27:24
【问题描述】:

我知道已经有几个关于这个主题的问题得到了解答,但没有一个可以帮助我解决我的问题。请记住,我刚刚开始学习 C++ 编程。

我正在创建一个程序来读取文本,然后将其显示在 N 行 x M 列中(由用户输入)。因此,如果用户编写 HarryPotter 并希望它显示在 3 x 4 数组中,它应该看起来像这样:

H a r r
y P o t
t e r

我已经用这段代码做到了:

cout << "Number of rows: ";
cin >> nr;
cout << "Number of columns: ";
cin >> nc;
cout << "Type in text: ";
cin >> text;

char letters[100][100];

for (int row = 0; row < nr; row++)
{
    for (int col = 0; col < nc; col++)
    {
        letters[row][col]= text [i];
        i++;
    }   
}

cout << "Print array: " << endl;
for (int row = 0; row < nr; row++)
    {
        for (int col = 0; col < nc; col++)
        {
            cout << letters[row][col];
        }

    cout << "\n";
    }

在用户写出多个单词之前,它都能正常工作。例如,他写了 Harry Potter 而不是 HarryPotter(我认为单词之间的空格是造成问题的原因)。你知道为什么会发生这种情况,我该如何解决?非常感谢。

【问题讨论】:

  • 可变文本是如何定义的?如果二维数组的元素总数大于文本中的字符数怎么办?
  • 您还应该在输入文本的末尾添加 null 终止
  • 我怀疑std::getline 很快就会出现在你的未来。
  • 你应该像here一样使用cin.getline()

标签: c++ arrays string algorithm multidimensional-array


【解决方案1】:

问题是operator &gt;&gt; 在流中遇到空白字符时停止输入字符串。您应该改用标准函数std::getline

考虑到显示字符串不需要定义数组。该任务可以在不使用数组的情况下完成。

这是一个演示程序。

#include <iostream>
#include <string>
#include <limits>
#include <algorithm>

int main() 
{
    while ( true )
    {
        std::cout << "Number of rows (0 - exit): ";

        unsigned int rows;
        if ( not ( std::cin >> rows ) or ( rows == 0 ) ) break;

        std::cout << "Number of columns (0 - exit): ";

        unsigned int cols;
        if ( not ( std::cin >> cols ) or ( cols == 0 ) ) break;

        std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

        std::cout << "Type in text: (Enter - exit): ";

        std::string text;
        std::getline( std::cin, text );
        if ( text.empty() ) break;

        std::cout << std::endl;

        std::string::size_type n = text.size();

        n = std::min<std::string::size_type>( n, cols * rows );

        for ( std::string:: size_type i = 0; i < n; i++ )
        {
            std::cout << text[i];

            std::cout << ( ( i + 1 ) % cols == 0 ? '\n' : ' ' );
        }

        std::cout << std::endl;
    }

    return 0;
}

它的输出可能看起来像

Number of rows (0 - exit): 3
Number of columns (0 - exit): 4
Type in text: (Enter - exit): HarryPotter

H a r r
y P o t
t e r

Number of rows (0 - exit): 2
Number of columns (0 - exit): 6
Type in text: (Enter - exit): HarryPotter

H a r r y P
o t t e r 

Number of rows (0 - exit): 6
Number of columns (0 - exit): 2
Type in text: (Enter - exit): HarryPotter

H a
r r
y P
o t
t e
r 

Number of rows (0 - exit): 4
Number of columns (0 - exit): 4
Type in text: (Enter - exit): Antonella Masini 

A n t o
n e l l
a   M a
s i n i

Number of rows (0 - exit): 0

您可以替换此语句

if ( not ( std::cin >> rows ) or ( rows == 0 ) ) break;

对于这个声明

if ( !( std::cin >> rows ) || ( rows == 0 ) ) break;

如果编译器没有编译第一条语句。如果你使用 MS VC++,那么在项目的属性中你应该关闭使用语言扩展(C++,语言),语句将被编译。

【讨论】:

  • 嗨,谢谢你的回复,但是当我把它放在我的代码中时,它说它不能识别变量 not...
  • @AntonellaMasini 你用什么编译器?
  • @AntonellaMasini 在任何情况下你都可以写 if ( !( std::cin >> rows ) || ( rows == 0 ) ) break;
  • 再问一个问题(如果您不介意的话)这是为了什么? cin.ignore(numeric_limits::max(), '\n');你认为通过这段代码我可以构建一些行来允许用户替换他们之前输入的文本中的一个单词吗?
  • 这是什么意思? cout
【解决方案2】:

cin 会将HarryPotter 之间的空格视为分隔符,并且仅将Harry 保存在text 中。

使用cin.getline,将读取整行,直到按下Enter 键。因此,cin.getline(text, sizeof(text))Harry Potter 将保存在text 中。

【讨论】:

  • 谢谢你的回答,但我只需要替换我的“cin >> text;”用“cin.getline(文本,s​​izeof(文本));” ?因为我试过了,但它不允许我运行程序,因为它说“没有重载函数的实例......与参数列表匹配”......
  • 你也可以使用getline(cin , string)
  • cin.getline(czTmp, row * col) 你用过的应该没问题。理想情况下,czTmp 应该分配 (row*col) 个字节。
【解决方案3】:

您可以使用动态字符数组,以便在运行时将其大小调整为用户输入的行和列:

#include <iostream>
using namespace std;

int main()
{
    int row, col;

    cout << "Row: ";
    cin >> row;
    cout << "Col: ";
    cin >> col;

    char** cText = new char*[row];
    for(int i(0); i < row; i++)
        cText[i] = new char[col];

    cin.sync(); // clearing the input buffer
    cout << "Text: ";

    char czTmp[100];
    cin.getline(czTmp, row * col); // getting user input text which fits to our 2d array of chars

    int k = 0;
    for(int i = 0; i < row; i++)
    {
        for(int j = 0; j < col; j++)
        {
            cText[i][j] = czTmp[k]; // inputting our array
            k++;
        }
    }

    cText[row - 1][col - 1] = '\0'; // adding a null-terminator because it is not added automatically

    // printing our array
    for(int i = 0; i < row; i++)
    {
        for(int j(0); j < col; j++)
            cout << cText[i][j];
        cout << endl;
    }

    // don't forget to free memory created by new

    for(int i(0); i < row; i++)
        delete[] cText[i];
    delete[] cText;
    cout << endl << endl;
    return 0;
} 

【讨论】:

  • 感谢您的回答,但是当我使用您的代码时,输​​入列数后它崩溃了,您知道这是为什么吗?
猜你喜欢
  • 2015-12-21
  • 2016-02-22
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-11
  • 1970-01-01
相关资源
最近更新 更多