[英]Converting string to c-style string and detecting null terminating character
我正在嘗試使用c_str()將C ++字符串對象轉換為C樣式NULL終止的字符串,然后嘗試訪問單個字符,因為可以對c樣式的字符串完成此操作。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1("Alpha");
cout << str1 << endl;
const char * st = new char [str1.length()+1];
st = str1.c_str(); // Converts to null terminated string
const char* ptr=st;
// Manually Showing each character
// correctly shows each character
cout << *ptr << endl;
ptr++;
cout << *ptr << endl;
ptr++;
cout << *ptr << endl;
ptr++;
cout << *ptr << endl;
ptr++;
cout << *ptr << endl;
ptr++;
cout << "# Null Character :" << *ptr << endl;
// But below loop does not terminate
// It does not find '\0' i.e. null
while( ptr != '\0')
{
cout << "*ptr : "<< *ptr << endl;
ptr++;
}
return 0;
}
但是似乎它沒有在末尾添加“ \\ 0”,並且循環不會終止。 我要去哪里錯了?
可以使用代碼中顯示的循環訪問C風格的字符串(例如char * st =“ Alpha”;),但是當發生從字符串對象到C風格的字符串的轉換時,它不會。我該怎么辦?
while( ptr != '\0')
應該
while (*ptr != '\0')
我認為您在這里缺少星號:
while( ptr != '\\0')
使它
while( *ptr != '\\0')
您還可以像這樣訪問string
每個單獨元素:
string helloWorld[2] = {"HELLO", "WORLD"};
char c = helloWorld[0][0];
cout << c;
您還可以遍歷string
:
string str ("Hello World");
string::iterator it;
for (int index = 0, it = str.begin() ; it < str.end(); ++it)
cout << index++ << *it;
要么
string str ("Hello World");
string::iterator it;
for (int index = 0, it = str.begin() ; it < str.end(); ++it, ++index)
cout << index << *it;
要么
string str ("Hello World");
string::iterator it;
int index = 0;
for (it = str.begin() ; it < str.end(); ++it, ++index)
cout << index << *it;
了解您正在尋找C風格的字符串中的以空字符結尾的字符,但是如果您有druthers,請繼續使用std :: string。
應該
while( *ptr != '\0')
{
cout << "*ptr : "<< *ptr << endl;
ptr++;
}
和
const char * st = new char [str1.length()+1];
st=str1.c_str();//Converts to null terminated String
應該
char * st = new char [str1.length()+1];
strcpy(st, str1.c_str());//Copies the characters
或者可能是
const char * st = str1.c_str();//Converts to null terminated String
您的版本是兩者的不良組合,因為它分配內存的方式就好像要復制字符一樣,但是不會復制任何內容。
您知道您也可以訪問std::string
的各個字符嗎? 只是str1[0]
, str1[1]
, str1[i]
等。
效果很好。謝謝您的回復。
int main()
{
string str1("Alpha");
cout << str1 << endl;
const char * st = new char [str1.length()+1];
st=str1.c_str();
//strcpy(st, str1.c_str());//Copies the characters
//throws error:
//Test.cpp:19: error: invalid conversion from `const char*' to `char*'
//Test.cpp:19: error: initializing argument 1 of `char* strcpy(char*, const char*)'
const char* ptr=st;
while( *ptr != '\0')
{
cout << "*ptr : "<< *ptr << endl;
ptr++;
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.