How to detect if user inserts data with commas (in a desired format) or not?

前端 未结 3 1689
野的像风
野的像风 2021-01-17 05:03

User inserts data in a format:\" [NAME], [SURNAME], [INDEX] \". Errors codes:
0 -- everything is loaded to the structure properly
1 -- not loaded to structure pr

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-17 05:25

    I would use this pseudo-code:

    isolate first comma-separated token
    if no token, return 1
    if length >= sizeof(s.name), return 1
    copy first token to s.name
    isolate second token
    if no token, return 2
    if length >= sizeof(s.surname), return 2
    copy first token to s.surname
    isolate third token
    if no token, return 3
    if token not numeric, return 3
    set s.index = atoi( third token )
    return 0
    

    If you code that up in C, you should end up with something nice and short and clean and reliable, without too many annoyingly redundant checking and backtracking.

    (Actually, if it was me, I'd use one general-purpose function to do the token isolating all at once, up front, then simply test if the number of found tokens was 0, 1, 2, 3, or more than 3. See this web page for additional ideas.)

提交回复
热议问题