簡體   English   中英

在二維數組 C++ 中存儲特定文件的單詞

[英]Storing words of specific file in 2D Array C++

努力將單詞存儲在 2D 數組中,當我使用char 時它工作正常但是當我使用下面的邏輯來存儲字符串時,我感到困惑

代碼:

string word;
int rows ,column;
string arr[10][20];
 fstream myFile("name.txt"); 

  while(myFile>>word)
   {
   arr[rows][column]=word;
    }

在這里,我被困在區分黑白行和列的算法是什么。

名稱.txt:

    It's steve 
    Studying CPP
    and steve loves cooking 

另外,一旦找到微分算法,我想將此文件的出現顯示為二維數組

您應該使用std::vector而不是數組,因為std::vector是一個可變大小的容器,並且您並不總是知道 input.txt 文件包含多少個元素。 完整的工作程序下面展示了如何實現你想要使用的是什么2D std::vector

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include<fstream>
int main() {
    std::string line, word;

    
    std::ifstream inFile("input.txt");
    
    //create/use a std::vector instead of builit in array 
    std::vector<std::vector<std::string>> vec;
    
    if(inFile)
    {
        while(getline(inFile, line, '\n'))        
        {
            //create a temporary vector that will contain all the columns
            std::vector<std::string> tempVec;
            
            
            std::istringstream ss(line);
            
            //read word by word 
            while(ss >> word)
            {
                //std::cout<<"word:"<<word<<std::endl;
                //add the word to the temporary vector 
                tempVec.push_back(word);
            
            }      
            
            //now all the words from the current line has been added to the temporary vector 
            vec.emplace_back(tempVec);
        }    
    }
    
    else 
    {
        std::cout<<"file cannot be opened"<<std::endl;
    }
    
    inFile.close();
    
    //lets check out the elements of the 2D vector so the we can confirm if it contains all the right elements(rows and columns)
    for(std::vector<std::string> &newvec: vec)
    {
        for(const std::string &elem: newvec)
        {
            std::cout<<elem<<" ";
        }
        std::cout<<std::endl;
    }
    
    /*another way to print out the elements of the 2D vector would be as below 
    for(int row = 0; row < vec.size(); ++row)
    {
        for(int col = 0; col < vec.at(row).size(); ++col)
        {
            std::cout<<vec.at(row).at(col)<<" ";
        }
        std::cout<<std::endl;
    }
    */
    
    return 0;
}

上面程序的輸出可以在這里看到。 在我的程序結束時,我打印了2d 向量的元素,以便我們可以確認它是否正確包含了所有元素。

好吧,首先,我認為您忘記了初始化rowscolumn 但除此之外, string s 自己管理字符數組,因此您不需要它們的 2D 數組,而是一個簡單的 1D 數組。

像這樣:

string word;
int rows = 0;
string arr[10];
fstream myFile("name.txt"); 

while(myFile>>word)
{
   arr[rows] = word;
   rows++;
}

暫無
暫無

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

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