本文目錄一覽:
C語言輸入帶空格的字元串的處理
用 scanf(“%s”,array); 的話遇到空格就停止接收後面的字元了
以下是處理這種情況的一些方法(記錄下來以免以後遇到相似的問題):
注 : %[abc] 表示字元組合包括 a、b和c ,如果遇到這三個字元之外的字元,則停止接收。 %[^abc] 代表字元組合為 abc 以外的所有字元,至於橫杠是否用於指定某個範圍的字元 %[a-z] ,則因編譯器而異。
c語言麻煩幫忙解決空格問題!謝謝大神們
#include stdio.h
#includestdlib.h
#include string.h
struct student
{
int number;
char name[20];
char sex;
double brith;
}stu[2];
int main()
{
int i;
printf(“Input student information:\n”);
for(i=0;i2;i++)
{
scanf(“%d %s %c %lf”,stu[i].number,stu[i].name,stu[i].sex,stu[i].brith);
}
if(stu[0].brithstu[1].brith)
printf(“number:%d\nname:%s\nsex:%c\nbrith:%.4f\n”,stu[0].number,stu[0].name,stu[0].sex,stu[0].brith);
else
printf(“number:%d\nname:%s\nsex:%c\nbrith:%.4f\n”,stu[1].number,stu[1].name,stu[1].sex,stu[1].brith);
system(“PAUSE”);
return EXIT_SUCCESS;
}
C語言中去掉空格問題
/*去除字元串右邊空格*/
void
vs_strrtrim(char
*pstr)
{
char
*ptmp
=
pstr+strlen(pstr)-1;
while
(*ptmp
==
‘
‘)
{
*ptmp
=
‘\0’;
ptmp–;
}
}
/*去除字元串左邊空格*/
void
vs_strltrim(char
*pstr)
{
char
*ptmp
=
pstr;
while
(*ptmp
==
‘
‘)
{
ptmp++;
}
while(*ptmp
!=
‘\0’)
{
*pstr
=
*ptmp;
pstr++;
ptmp++;
}
*pstr
=
‘\0’;
}
c語言中把文件中的空格去除
第一種:使用位域限制讀取的長度;
第二種:可以直接按照結構體來讀寫;
實例代碼如下:
#include “stdafx.h”
#include cstdio
#include cstdlib
#include cstring
struct Roommate{
char name[6];
char NO[8];
char addr[10];
};
int _tmain(int argc, _TCHAR* argv[])
{
struct Roommate Rom[2] = {0};
FILE *file = NULL;
if(!(file = fopen(“a.txt”, “w”))) {
printf(“Create File failed!\n”);
exit(-1);
}
printf(“Please input four times Roommate data: Name NO Addr\n”);
for(int i=0; i2; ++i) {
scanf(“%s%s%s”, Rom[0].name, Rom[0].NO, Rom[0].addr);
fwrite((const void *)Rom[0], sizeof(struct Roommate), 1, file);
}
fclose(file);
/* Read from file*/
file = NULL;
if(!(file = fopen(“a.txt”, “r”))) {
printf(“Create File failed!\n”);
exit(-1);
}
printf(“Read from the file: Name NO Addr\n”);
fread((void *)Rom, sizeof(struct Roommate), 2, file);
for(int i=0; i2; ++i) {
printf(“i=%d Name:%s\tNO:%s\tAddr:%s\n”, i, Rom[i].name, Rom[i].NO, Rom[i].addr);
}
fclose(file);
while(getchar()) ;
return 0;
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/254513.html