[英]When I read from a file I am getting control characters
我正在嘗試從文件中讀取數據,但我一直在字符串末尾獲取控制字符。 我使用for
循環來檢查它們並打印出每個單詞都有一個,但temp.size()
是我將+ 1
添加到temp.size()
。 我不想從文件中讀取它們。 我真的很困惑為什么會這樣。
int main(){
ifstream inFile;
vector<string> vect;
string temp = "";
//Reading from a file line by line
inFile.open("words.txt");
if (inFile.is_open())
{
while (!inFile.eof())
{
getline(inFile, temp);
vect.push_back(temp);
}
}
inFile.close();
//checking through each character of the string to see if it has a control character.
for (int i = 0; i < vect.size(); i++)
{
temp = vect[i];
for (int j = 0; j < temp.size() + 1; j++)
{
if (iscntrl(temp[j]))
{
cout << temp << " There is a space\n";
}
}
}
return 0;
}
您問題的根本原因是您的for
循環正在訪問temp
字符串的空終止符(從技術上講,在 C++11 之前,這是未定義的行為)。 iscntrl()
將字符'\\0'
(0x00) 視為控制字符。 你需要改變這個:
for (int j = 0; j < temp.size() + 1; j++)
對此:
for (size_t j = 0; j < temp.size(); j++)
空終止符不是std::string
大小/有效負載的一部分,但它的存在是為了兼容性,以便std::string
可以與基於 C 的 API 一起使用。
此外,與該問題無關,您的while
循環已損壞。 請參閱為什么 iostream::eof 在循環條件內(即`while (!stream.eof())`)被認為是錯誤的? . 你需要替換這個:
while (!inFile.eof())
{
getline(inFile, temp);
vect.push_back(temp);
}
有了這個:
while (getline(inFile, temp))
{
vect.push_back(temp);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.