2017-02-11 90 views
-5

我有一個字符串數組std::string words[4000]充滿隨機單詞。我想檢查此數組中任何隨機單詞的大小。我想:C++如何檢查字符串數組內的元素的大小?

int x = words[rnd].length(); 

int x = words[rnd].size();

int x = sizeof(words[rnd]);

其中RND是()的返回蘭特一些。但是這兩次x的值都是0,sizeof()總是返回28.我在這裏做錯了什麼?

的人誰願意來檢查全碼:

#include <iostream> 
#include <fstream> 
#include <string> 
#include <time.h> 
#include <stdlib.h> 
std::string words[4000];  ` 
void fread(std::string fname, std::string words[], const int & nwords) 

    { 

     std::ifstream ifile(fname.c_str(), std::ios::in); 

     if (!ifile) 
     { 
      std::cout << " Couldn’t read the file " << fname; 
      exit(-1); 
      //return; 
     } 

     int count = 0; 
     while (ifile && count < nwords) 
      ifile >> words[count++]; 
     ifile.close(); 
    } 

    `int main()` 
    `{` 

     srand(time(NULL)); 
     int nwords = 4000; 
     int rnd = rand() % nwords; 
     int x = words[rnd].length()/3; 
     fread("<location>", words, nwords); 
     int* hintloc = new int[x]; 
     std::cout << words[rnd]; //this checks whether i have the right word 
     const int hangsize = 19; 
     bool chk; 
     std::cout << "\n\n\t\t\tGET READY FOR HANGMAN!\n\n\t\tGuess this word: "; 
     for (int i = 0; i < x; i++) 
     { 
      hintloc[i] = rand() % words[rnd].size(); 
      for (int j = 0; j < i; j++) 
      { 
       if (hintloc[i] == hintloc[j]) 
        i--; 
      } 
     } 

     for (int i = 0; i < words[rnd].size(); i++) 
     { 
      chk = true; 
      for (int j = 0; j < x; j++) 
      { 
       if (i == hintloc[j]) 
       { 
        std::cout << words[rnd].at(i)<<" "; 
        chk = false; 
       } 
      } 
      if (chk == true) 
       std::cout << "_ "; 
     } 

     delete[] hintloc; 
     system("pause"); 
     return 0; 
    } 
+0

你確定'rnd'是否在0..3999之內? – gurka

+0

另外,sizeof(std :: string)'不會給你字符串的長度。它將返回'string'類/結構的大小,以字節爲單位。 – gurka

+0

你如何初始化單詞? –

回答

0

實際上,你需要初始化數組words這樣的元素具有非零長度,使用這些元素之前。如果你不這樣做,元素將被默認初始化。默認初始化的std::string將有length()size()成員都給出零結果(因爲他們做同樣的事情)。

如果您正在從文件中讀取字符串,並稍後檢查顯示它們長度爲零,則文件包含所有零長度的字符串或讀取文件時發生錯誤。

sizeof(words[rnd])給出sizeof std::string,這是std::string類型的大小。這與std::string(例如words[rnd])的任何實際實例所保存的字符串數據的大小沒有關係。

+0

我已經多次驗證字符串正在從文件中讀取並保存到數組'字'中。然而,返回的大小仍然是0.並且文件不是空的。在讀取文件之前初始化爲不同的值會返回我初始化的長度,即使我在讀取txt文件後調用size()函數 –

+0

也許是這樣。但問題出在你的代碼和它的工作數據上,不管你是否在這裏展示它。但是,除非你提供了一個表明你的總問題的MCVE(即別人可以用來重新創建完全相同的問題) - 你沒有 - 人們別無選擇,只能指出這種可能性。但是,如果文件已被驗證爲正確讀取,並且字符串的'.size()'返回零,那麼推測您的驗證方法是有缺陷的。 – Peter

+0

所以我試着用'value',words [rnd] .size()'替換'x'的所有實例。由於某種原因,它正確地返回了相應字符串的長度值。顯然,問題在於將其分配給'x'。 –

相關問題