Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

visual studio 2010 - Max string length using scanf -> ANSI C

I have:

#define MAX_STR_LEN 100

and I want to put into scanf pattern so I can control the string length:

scanf("%100[^
]s",sometext)

I tried:

scanf("%MAX_STR_LEN[^
]s",sometext)
scanf("%"MAX_STR_LEN"[^
]s",sometext)
scanf("%",MAX_STR_LEN,"[^
]s",sometext)

And it didn't work. I just want to avoid buffer overflow since "sometext" is allocated with malloc(MAX_STR_LEN)...

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I wasn't happy with any of these solutions, so I researched further, and discovered GNU GCC macro stringification

which can be used as:

#define XSTR(A) STR(A)
#define STR(A) #A
#define MAX_STR_LEN 100
scanf("%"XSTR(MAX_STR_LEN)"[^
]s", sometext)

Maybe VS2010 offers something similar?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...