C++底带没有给我正确的结果
我有以下代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream file;
string s;
//file contains the following
//id="123456789"
//Note: There is no spaces at the end
file.open("test.txt", ios::in);
getline(file, s);
s = s.substr(s.find("\"")+1, s.length()-1);
cout << s << endl;
return 0;
}
结果打印:
123456789"
为什么最后有报价? 一个奇怪的是,当我将s.length()-1更改为s.length()-5时,代码工作我想要的。 这里有什么问题?
I have the following code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream file;
string s;
//file contains the following
//id="123456789"
//Note: There is no spaces at the end
file.open("test.txt", ios::in);
getline(file, s);
s = s.substr(s.find("\"")+1, s.length()-1);
cout << s << endl;
return 0;
}
The results print:
123456789"
Why is there a quote at the end?
A weird thing is that when I change s.length()-1 to s.length()-5, the code work how I wanted it to.
What is the problem here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
string :: subSttr()
< < /a>是A count ,而不是 index ,就像您正在对待它一样。在您的示例中,
s.length()= 14
,因此您要求14-1 = 13
字符从索引+1
开始过去的第一“ 字符(3+1 = 4
),但是从该位置开始只剩下10个字符。这就是为什么第二个“ 字符包含在子字符串中。
使用
String :: find()
再次查找第二个“
字符的索引,然后减去两个索引以获取它们之间的长度,例如:start
将是索引+1
超过第1 “ targine(3+1 = 4
)和停止
将是第二个“ targine(13
)的索引。因此,您获得的长度是13-4 = 9
。字符 /cpp/io/manip/引用“ rel =“ nofollow noreferrer”>
std ::引用
i/o操纵器以在之间提取substring ,例如:
The 2nd parameter of
string::substr()
is a count, not an index, like you are treating it.In your example,
s.length()=14
, so you are asking for14-1=13
characters starting at the index+1
past the 1st"
character (3+1=4
), but there are only 10 characters remaining from that position onward. That is why the 2nd"
character is being included in the substring.Use
string::find()
again to find the index of the 2nd"
character, and then subtract the two indexes to get the length between them, eg:start
will be the index+1
past the 1st"
character (3+1=4
), andstop
will be the index of the 2nd"
character (13
). Thus, the length you get is13-4=9
characters.Another way to handle this would be to put the
string
into anistringstream
and then use thestd::quoted
I/O manipulator to extract the substring between the"
characters, eg:表达式
s.length()-1
产生了整个字符串的长度,除了一个字符。您应该写作
,也可以写以下方式
The expression
s.length()-1
yields the length of the whole string except one character.You should write for example
Or you could write the following way