簡體   English   中英

C ++分割字符串會產生奇怪的輸出

[英]C++ splitting a string gives a weird output

我試圖split一個string ,它的工作原理。 只是當我將其打印到console我才得到一個奇怪的output -╨╕[╝。 也許有人可以暗示我做錯了什么? 這是我的代碼

#include <stdio.h>
#include <windows.h>
#include <string>
#include <sstream>
#include <vector>


using namespace std;

vector<string> &split(const string &s, char delim, vector<string> &elems);

vector<string> split(const string &s, char delim);

int main() {

    vector<string> x = split("E:\\TEST\\filename.txt", '\\');

    int pos = x.size() - 1;
    printf("filename is %s\n", &x.at(pos));

    system("PAUSE");

    return 0;
}

vector<string> &split(const string &s, char delim, vector<string> &elems) {
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}


vector<string> split(const string &s, char delim) {
    vector<string> elems;
    split(s, delim, elems);
    return elems;
}

使用printf("filename is %s\\n", x.back().c_str()); 打印字符串。

您的問題是您正在將字符串對象的地址發送給printf,但是printf需要以null終止的char數組。 成員函數c_str可以為您提供!

您將錯誤的參數傳遞給printf("%s") %s需要一個C字符串(即char *),但是您要向其傳遞C ++ std::string的地址。 這是未定義的行為。

您需要做的是通過調用其c_str()方法來確保獲取由std::vector<std::string>::at(int)返回的std::string的C字符串表示形式:

printf("filename is %s\\n", x.at(pos).c_str());

暫無
暫無

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

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