簡體   English   中英

在C ++中,如何從字符串(或char數組)中提取子字符串並將其寫入字符串,而不會收到警告?

[英]In C++, how to extract a substring from a string (or char array) and write it to a string, without getting warnings?

在C ++中,我正在讀取一個文件,其中的行是類似的

     65-82 0.015 0.655

其中第一個是字符串(由短划線或逗號分隔的數字,然后被處理)和兩個浮點數。 我正在使用以下代碼閱讀它們,[line]是一個字符數組:

std::string temp_string;
double temp_kb, temp_kt;
int res = sscanf(line, "%s %lf %lf",temp_string,&temp_kb,&temp_kt);

這會產生一個警告:

~/TEPInteraction.cpp:1002:76: warning: writing into constant object (argument 3) [-Wformat=]
int res = sscanf(line, "%s %lf %lf",temp_string.c_str(),&temp_kb,&temp_kt);
                                                                        ^

這當然有意義,因為c_str()返回一個常量指針。 如果沒有警告,這樣做的正確方法是什么?

非常感謝,費迪南多

編輯:需要res的值來進行更深入的控制,所以我將不得不簡單地重寫我的代碼,以便它不使用它。 這不是什么大不了的事,但它會等到明天。 謝謝你們:-)非常感謝你的幫助。

由於您的輸入是以空格分隔的,因此您可以使用文件流的>>運算符讀取輸入。

std::ifstream fin("my_file_to_read");
std::string data;
double a, b;
fin >> data >> a >> b;

以上將采取

65-82 0.015 0.655

從文件中輸入65-82data然后停在空間。 然后將0.015添加到a然后在空格處停止然后將0.655添加到b

如果您想確保每行有3個值,那么您的輸入以數字開頭,那么您需要使用std::getline從文件中讀取整行。 然后你可以將該行加載到std::stringstream並檢查提取是否成功。

std::ifstream fin("my_file_to_read");
std::string data, line;
double a, b;
std::getline(fin, line);
std::stringstream ss(line);
if (!(ss >> data >> a >> b))
{
    //error handling code here
}

在C ++中,您通常會執行以下操作:

std::istringstream stream(line);
std::string temp_string;
double temp_kb, temp_kt;
if (!(stream >> temp_string >> temp_kb >> temp_kt)) {
    // unable to read all values. handle error here
}

你不能寫這樣的字符串對象。 如果您真的想使用sscanf() ,則需要使用char[]數組,然后將其轉換為string

暫無
暫無

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

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