给vector取下标时出现的神奇问题
就是下面的程序,首先用户随意输入任意数目的字符串,当要结束的时候,就按Ctrl+Z.然后这些字符串就被储存在vector svec里面了。然后用户随意输入一个数index,那么程序将输出svec中第index个元素(当然,如果越界的话,就取模)。可是神奇的是,当我输入
a b c d e f g h
^z
后,再输入-1,却给我显示的是svec中第3个元素。我还发现这一现象与svec的元素数目无关。这究竟是怎么回事呢?如何解决呢?
vector 下标
//
#include <iostream>
#include <vector>
#include <string>
using std::string;
using std::vector;
using std::cin;
using std::cout;
using std::endl;
void keep_window_open();
int main()
{
vector<string> svec;
string s;
cout<<"\nNow please input any number of strings with no whitespace in the center."
<<"\nTo terminate, input Ctrl+z:\n"
<<endl;
while(cin>>s)
{
svec.push_back(s);
}
cin.clear();
vector<int>::size_type n=svec.size();
cout<<"\nActually, there are "<<n<<" elements in the vector svec now.\n";
if(n>0)
{
vector<int>::size_type index;
cout<<"\nNow please input any integer between 1 and "<<n
<<".\nYes, as you may have guessed, I will show you the corresponding element of vector svec.\n"
<<endl;
cin>>index;
while(index<=0)
{
cout<<"\nMake sure to input a positive integer, OK? Try again:\n";
cin>>index;
}
index=index%n;
if(index==0) index=index+n;
cout<<"\nSo the "<<index<<"th element of vector svec is "
<<svec[index-1]<<endl;
}
keep_window_open();
}
void keep_window_open()
{
cout << "\nPress any key to exit:";
getchar();
}
#include <stdio.h>
char s[]="123 ab 4";
char *p;
int v,n,k;
void main() {
p=s;
while (1) {
k=sscanf(p,"%d%n",&v,&n);
printf("k,v,n=%d,%d,%d\n",k,v,n);
if (1==k) {
p+=n;
} else if (0==k) {
printf("skip char[%c]\n",p[0]);
p++;
} else {//EOF==k
break;
}
}
printf("End.\n");
}
//k,v,n=1,123,3
//k,v,n=0,123,3
//skip char[ ]
//k,v,n=0,123,3
//skip char[a]
//k,v,n=0,123,3
//skip char[b]
//k,v,n=1,4,2
//k,v,n=-1,4,2
//End.
#include <stdio.h>
FILE *f;
int n,r,g;
int main() {
f=fopen("in.txt","r");
if (NULL==f) {
printf("Can not open file in.txt!\n");
return 1;
}
n=0;
while (1) {
g=0;
r=fscanf(f,"abcde%n",&g);
if (5==g) n++;
else if (0==r) fgetc(f);
else break;
}
fclose(f);
printf("%d time(s) "abcde" in file in.txt.\n",n);
return 0;
}