Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么它给了我一个错误的索引_C++ - Fatal编程技术网

C++ 为什么它给了我一个错误的索引

C++ 为什么它给了我一个错误的索引,c++,C++,这是文本 “Abraham,Yohannes A.”,雇员 我要第二个逗号的索引 这是我的代码intfoundstatus=tempString.find_first_of(“,”,8) 我认为这将返回索引8后的第二个逗号的索引,即22,但是当我给我-1时,你需要使用9作为第二个参数,而不是8(假设你的字符串是:“\”Abraham,Yohannes A.\”,Employee,)。 否则它只返回8,而不是22。 返回值(-1)表示之后找不到任何逗号-请检查输入字符串两次,在位置8之后确实有第二

这是文本

“Abraham,Yohannes A.”,雇员

我要第二个逗号的索引

这是我的代码
intfoundstatus=tempString.find_first_of(“,”,8)

我认为这将返回索引8后的第二个逗号的索引,即22,但是当我给我-1时,你需要使用9作为第二个参数,而不是8(假设你的字符串是:
“\”Abraham,Yohannes A.\”,Employee,
)。 否则它只返回8,而不是22。 返回值(-1)表示之后找不到任何逗号-请检查输入字符串两次,在位置8之后确实有第二个逗号

以下代码将正确输出22:

#include <iostream>
#include <string>

int main(int argc, char* argv[]){
  std::string tempString = "\"Abraham, Yohannes A.\", Employee, ";
  size_t firstComma = tempString.find_first_of(","); // firstComma = 8
  if (firstComma != std::string::npos) {
    size_t secondComma = tempString.find_first_of(",", firstComma+1);  // secondComma = 22
    std::cout << secondComma << std::endl;
  }
  return 0;
}
#包括
#包括
int main(int argc,char*argv[]){
std::string tempString=“\”亚伯拉罕,约哈内斯A.\”,雇员“;
size\u t firstComma=tempString.find\u first\u of(“,”;//firstComma=8
if(firstComma!=std::string::npos){
size\u t secondComma=tempString.find\u first\u of(“,”,firstComma+1);//secondComma=22

std::cout您如何初始化
tempString
?它可以工作。显示完整的代码以重现此问题。哦-我确信OP已与其调试器进行了检查,以确保“tempString”包含如上所述的确切文本………等待是
,雇员是
,否则它将在
A之后停止。
>是的,它在字符串内部。整个临时字符串是“Abraham,Yohannes A.”,员工,年薪120000.00美元,总统特别助理兼公共参与和政府间事务办公室办公室办公室主任。因此,我认为在位置8i后有逗号。我使用9或更大,但仍然返回-1,以及为什么添加\“在临时字符串tho中?哦,妈的,我刚发现临时字符串后面没有任何元素8@ckmss因为必须转义文本字符串中的双引号。