2013-03-04 3 views
-1

Моя строка d отображается пустым (даже не пробелом) на моей консоли, это меня путает, так как я инициализировал ее до «NULL», и я пытаюсь присвоить ей новое значение, которое не является пустым значением.Моя инициализированная переменная отображается пустой

int main(){ 

    string user_String[99]; 
    int user_Input = 0; 

    cout << "Please insert up to one hundred Strings: "; 
    cin >> user_Input; 


    //Check for range 
    bool check = false; 
    while(check == false){ 
     if (user_Input < 1 || user_Input >100){ 
      cout << "Please insert up to one hundred Strings: "; 
      cin >> user_Input;} 
     else{ 
      check = true; 
      break;} 
    } 

    //User input 
    cout <<"Please enter string"<< endl; 
    for (int counter = 0; counter < user_Input; counter++){ 
     int counter2 = counter + 1; 
     cout << "Enter String " << counter2 << ": "; 
     cin >> user_String[counter]; 
    } 

    //Loopig for most letters 
    string c = "NULL"; 
    for(int counter = 0; counter < user_Input; counter++){ 
     //Making Sure Coun doesn't go out of range 
     int coun = 0; 
     if (counter < user_Input){ 
      coun = counter +1;} 
     else{ 
      coun = counter; 
     } 

     string a = user_String[counter]; 
     string b = user_String[coun];  

     if (a.length() < b.length() && c == "NULL"){ 
      c = b; 
     } 

     if(a.length() < b.length() && c!="NULL" && c.length() < b.length()){ 
      c = b; 
     } 
     else{ 
      continue; 
     } 

    } 
    cout << "The string "<< c <<" have the most letters." << endl; 

    //Looping for least letters 
    string d = "NULL"; 
    for(int counter = 0; counter < user_Input; counter++){ 
     //Making Sure Coun doesn't go out of range 
     int coun = 0; 
     if (counter < user_Input){ 
      coun = counter +1;} 
     else{ 
      coun = counter; 
     } 

     string a = user_String[counter]; 
     string b = user_String[coun]; 

     if (a.length() > b.length() && d == "NULL"){ 
      d = b; 
     } 

     if(a.length() > b.length() && d!="NULL" && d.length() > b.length()){ 
      d = b; 
     } 
     else{ 
      continue; 
     } 
    } 
    cout << "The string " << d <<" have the least letters." << endl; 


    system("pause"); 
    return 0; 
} 
+1

Я хотел бы получить очень смущен, если программа сказал мне введите строки и ожидайте целое число. – chris

+1

Как вы можете быть уверены, что новое значение, которое вы ему назначили, не пусто? Я бы рекомендовал пройти через отладчик, чтобы увидеть, что на самом деле происходит. –

ответ

1

Вы позволяете пользователю ввести до 100 строк, но ваш массив может содержать только до 99 строк. Если они на самом деле вводят 100 строк, последняя строка испортит память, предположим, что ваш код вообще не падает.

Кроме того, ваши петли писем имеют в них ошибочную логику. if (counter < user_Input) всегда будет истинным, поэтому coun всегда будет counter+1 и, таким образом, превысит границы массива, когда counter достигнет конца массива. Кроме того, ваши петли излишне сложны для того, что они пытаются сделать.

Попробуйте вместо этого:

int main() 
{ 
    string user_String[100]; 
    int user_Input; 

    do 
    { 
     cout << "Please enter the number of Strings (1-100): "; 
     if (cin >> user_Input) 
     { 
      if ((user_Input >= 1) && (user_Input <= 100)) 
       break; 
     } 
     else 
      cin.clear(); 
    } 
    while (true); 

    for (int counter = 0; counter < user_Input; ++counter) 
    { 
     cout << "Enter String " << counter + 1 << ": "; 
     cin >> user_String[counter]; 
    } 

    string b = user_String[0]; 
    for(int counter = 1; counter < user_Input; ++counter) 
    { 
     string a = user_String[counter]; 
     if (a.length() > b.length()) 
      b = a; 
    } 

    cout << "The string " << b << " has the most letters." << endl; 

    b = user_String[0]; 
    for(int counter = 1; counter < user_Input; ++counter) 
    { 
     string a = user_String[counter]; 
     if (a.length() < b.length()) 
      b = a; 
    } 

    cout << "The string " << b <<" has the least letters." << endl; 

    system("pause"); 
    return 0; 
} 

С учетом сказанного, вы можете избавиться от массива в целом и объединить петли вместе:

int main() 
{ 
    string user_String; 
    int user_Input; 

    do 
    { 
     cout << "Please enter the number of Strings: "; 
     if (cin >> user_Input) 
     { 
      if (user_Input >= 1) 
       break; 
     } 
     else 
      cin.clear(); 
    } 
    while (true); 

    string fewestLetters, mostLetters; 
    for (int counter = 1; counter <= user_Input; ++counter) 
    { 
     cout << "Enter String " << counter << ": "; 
     cin >> user_String; 

     if (counter == 1) 
     { 
      mostLetters = user_String; 
      fewestLetters = user_String; 
     } 
     else 
     { 
      if (user_String.length() > mostLetters.length()) 
       mostLetters = user_String; 

      if (user_String.length() < fewestLetters.length()) 
       fewestLetters = user_String; 
     } 
    } 

    cout << "The string " << mostLetters << " has the most letters." << endl; 
    cout << "The string " << fewestLetters << " has the least letters." << endl; 

    system("pause"); 
    return 0; 
} 
+1

Во втором примере не было бы минимальных значенийLetters всегда длина 0 и, следовательно, никогда ничего не назначалось? Я бы добавил check! Empty(), чтобы удостовериться, что первая строка привязана к ней, чтобы начать катить мяч. –

+0

@RetiredNinja: хороший улов. –

+0

Если вы введете 'a' в число строк, это перейдет в бесконечный цикл. Попробуйте 'while (! (Std :: cin >> user_Input)) {std :: cin.clear(); std :: cout << "Введите число строк (1-100):";} ' –

Смежные вопросы