簡體   English   中英

將字符串輸入多維數組

[英]Inputting string into multidimensional array

我正在嘗試制作一個包含多個用戶輸入字符串的數組,我已經厭倦了結構和動態數組,但是它不起作用

我嘗試制作一個包含字符串的結構,並嘗試制作該結構的數組,但它不起作用

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



using namespace std;

int main()
{
    int rows;
    cin >> rows;
    string **arr = new string*[rows];
    for( int i = 0; i < rows; ++i)
    {
        arr[i]= new string[1];
    }
    for(int i = 0; i < rows; ++i)
    {
        getline(cin, arr[i][0]);
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }


    for(int i = 0; i < rows; ++i)
    {
        cout << arr[i][0] << '\n';
    }


    for( int i = 0; i < rows; ++i)
    {
        delete [] arr[i];
    }
    delete [] arr;
return 0;
}

它允許行+ 1輸入然后崩潰

使用std :: vector和std:string類型輕松完成工作:

#include <iostream>
#include <string>
#include <limits>
#include <vector>

using namespace std;

int main()
{
    int rows;
    cin >> rows;
    std::vector<std::string> vec;
    std::string s;

    // flush cin
    std::getline(std::cin, s);


    for (int i = 0; i < rows; ++i)
    {
        std::getline(std::cin, s);
        vec.push_back(s);
    }


    for (int i = 0; i < rows; ++i)
    {
        cout << vec[i] << '\n';
    }

    return 0;
}
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');

如果有錯誤,應該這樣做,而不是常規情況。

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM