字符串的反转:
#include<iostream>
#include<cstring>
using namespace std;
void mystrrev(char * string){
int len=strlen(string);
char *p=string,*q=string+len-1;
char tmp;
for(int i=0;i<len/2;i++){
tmp=*p;
*p=*q;
*q=tmp;
p++;
q--;
}
}
int main(){
char str[100];
cout<<"input string:";
cin>>str;
mystrrev(str);
cout<<"output string:"<<str<<endl;
return 0;
}
文本读取查询规范:
#include<iostream>
#include<fstream>
using namespace std;
int main(){
char id[12],str[80];
bool name,cla;
ifstream in;
in.open("data.txt");
if(!in){
cout<<"cannot open file.";
return 1;
}
while(in){
int i=0;
in.getline(str,80);
while(str[i]!=','){
id[i]=str[i];
i++;
}
id[i]=0;
i++;
name=false,cla=false;
while(str[i]!=','){
if(str[i]!=' ' && str[i]!= '\t' ) name=true;
i++;
}
i++;
while(str[i]!=0){
if(str[i]!=' ' && str[i]!='/t') cla=true;
i++;
}
if(in && !name && cla) cout<<"学生"<<id<<":"<<"缺少姓名信息"<<endl;
if(in && name && !cla) cout<<"学生"<<id<<":"<<"缺少班级信息"<<endl;
if(in && !name && !cla) cout<<"学生"<<id<<":"<<"缺少姓名,班级信息"<<endl;
}
cout<<endl;
in.close();
return 0;
}
data.txt中的内容:
11111111,,1班
22222222,xxx,
33333333,,2班
44444444,zzz,3班
55555555,,
转载的动态内存分配:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* upcase(char *inputstring);
int main(void){
char *str1;
str1 = upcase("hello");
printf("str1=%s \n",str1);
free(str1);
return 0;
}
char* upcase(char *inputstring)
{
char *newstring;
int counter;
if(!(newstring=(char *) malloc(strlen(inputstring)+5)))
{
printf("Error malloc !\n");
exit(1);
}
strcpy(newstring,inputstring);
for(counter =0; counter < strlen(newstring); counter++){
if(newstring[counter] >= 97 && newstring[counter] <=122)
{
newstring[counter] -= 32;
}
}
return newstring;
}