簡體   English   中英

為什么字符串的末尾會有問號?

[英]Why is there a question mark at the end of the string?

請幫助我弄清楚為什么我的字符串輸出中有一個問號。 我一直在進行這種簡單的反向字符串練習。 我的代碼可以正確執行。 然后,我嘗試將反向字符串存儲到數組中,然后將此數組轉換為字符串。 所以這是發生了一些事情。 該字符串的末尾始終會有一個問號。 請教我原因,以及如何消除此問號。 這是我的代碼。 非常感謝

#include <string>
using namespace std;

int main()
{
    cout<<"Please enter a string."<<endl;
    string str;
    cin >> str;
    int i=0;
    int length = str.length();
    char arr[length];
    //cout<<length;
    while (length != 0) {
        arr[i] = str.at(length-1);
        length--;
        cout<<arr[i];
        ++i;
    }
    cout<<endl;
    string stri(arr);
    cout<<endl<<stri<<endl;
    cout<<stri[4];
    return 0;
}

C(或許多其他語言)的字符串需要以'\\0'結尾。 畢竟,您不知道char*指向多大的內存。 因此,您需要char[length + 1] 同樣, 可變長度數組也不是C ++的一部分。 您需要使用new[]/delete[]malloc()/free()

char * arr = new char[length + 1]; // enough space for string + '\0'
char[length] = '\0';               // terminate the string with '\0'

while (length != 0) {
    // ...                         // reverse
}
cout << endl;

string stri(arr);                  // create the new string

delete[] arr;                      // don't forget to deallocate the memory

但是,如果您要進行手動內存分配,通常會從標准庫中丟失某些內容。 確實,您可以簡單地使用正確的構造函數 (為(4),下面進行了簡化):

template <class InputIt>
string::string(InputIt first, InputIt last);

幸運的是, std::string提供了輸入迭代器,該迭代器通過std::string::rbegin()std::string::rend()向后遍歷字符串。 現在,您的代碼變得容易得多:

#include <iostream>
#include <string>

int main()
{
    std::cout << "Please enter a string." << std::endl;

    std::string str;
    std::cin >> str;

    std::cout << std::endl;

    // Create the new reversed string directly:
    std::string reversed_string(str.rbegin(), str.rend());

    std::cout << reversed_string << std::endl;

    return 0;
}
char arr[length];

應該

char arr[length + 1];

編輯:或者更確切地說(正如喬納森·波特指出的那樣,由於length不是一個編譯時間常數,因此您的代碼可能只進行編譯,因為特定編譯器(例如GNU C ++)允許這樣做):

char *arr = new char[length + 1];

(並在某個時候delete [] arr;

存儲終止的“ \\ 0”:

arr[length] = '\0';

暫無
暫無

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

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