想从一串带有很多空格的字符串中将其中的整数提取出来,写如下代码,程序运行异常:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 10000
#define Capacity 1000
using namespace std;
int main()
{
void GetNum(char *Line,char *str,int *sub,int *data);
char str[100000];
char GetL[Capacity];
int data[MaxSize];
cout<<"请输入字符串:";
cin.getline(GetL,Capacity);
char *Line=GetL;
int sub=0;
GetNum(Line,str,&sub,data);
return 0;
}
void GetNum(char *Line,char *str,int *sub,int *data)
{
int index=0;
while(Line[index]!='\n'){
cout<<Line[index++];
}
}
输入:
123 456 789
运行后将该字符串输出,但紧接着,在运行界面的最底端又输出了下面的东西:
将GetNum函数中while里的判断条件由Line[index]!=’\n’改为Line[index]!=’\0’,程序能正常运行。
在这篇文章https://blog.csdn.net/zd_nupt/article/details/80436854?utm_source=distribute.pc_relevant.none-task中看到说,cin.getline()不会将结束符或换行符残留在输入缓冲区中,具体仍没大弄懂,先将问题记在这里