2

私のコードは、コンマで区切られた 2 つ以上の著者名を読み取り、最初の著者の姓を返す必要があります。

cout << "INPUT AUTHOR: " << endl ;
getline(cin, authors, '\n') ;

int AuthorCommaLocation = authors.find(",",0) ;
int AuthorBlankLocation = authors.rfind(" ", AuthorCommaLocation) ;

string AuthorLast = authors.substr(AuthorBlankLocation+1, AuthorCommaLocation-1) ;
cout << AuthorLast << endl ;

ただし、部分文字列を取得しようとすると、AuthorLast3 文字から 1 文字の長すぎるテキストが返されます。私のエラーへの洞察はありますか?

4

1 に答える 1

3

C++substrメソッドは、開始位置と終了位置を取りません。代わりに、開始位置と読み取る文字数を受け取ります。その結果、渡される引数はsubstr、 position から開始して、その位置から先の文字AuthorBlankLocation + 1を読み取るように指示していますがAuthorCommaLocation - 1、これはおそらく文字数が多すぎます。

string開始位置と終了位置を指定する場合は、コンストラクターのイテレーター バージョンを使用できます。

string AuthorLast(authors.begin() + (AuthorBlankLocation + 1),
                  authors.begin() + (AuthorCommaLocation - 1));

お役に立てれば!

于 2013-01-31T02:54:55.880 に答える