首页 > 解决方案 > How to print a substring in C

问题描述

simple C question here! So I am trying to parse through a string lets say: 1234567W

#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
    //pointer to open file
    FILE *op;
    //open file of first parameter and read it "r"
    op = fopen("TestCases.txt", "r");
    //make an array of 1000
    char x[1000];
    char y[1000];
    //declare variable nums as integer
    int nums;
    //if file is not found then exit and give error
    if (!op) {
        perror("Failed to open file!\n");
        exit(1);
    }
    else {
        while (fgets(x, sizeof(x), op)) {
            //pounter to get the first coordinate to W
            char *p = strtok(x, "W");
            //print the first 3 digits of the string 
            printf("%.4sd\n", p);
                
        }
    }
    return 0;

My output so far shows: "123d" because of the "%.4sd" in the printf function. I now need to get the next two numbers, "45". Is there a regex expression I can use that will allow me to get the next two digits of a string? I am new to C, so I was thinking more like "%(ignore the first 4 characters)(print next 2 digits)(ignore the last two digits)"

input: pic

output: pic

Please let me know. Thanks all.

标签: c

解决方案


printf("Next two: %.2s\n", p + 4);应该管用。

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
    //pointer to open file
    FILE *op;
    //open file of first parameter and read it "r"
    op = fopen("TestCases.txt", "r");
    //make an array of 1000
    char x[1000];
    char y[1000];
    //declare variable nums as integer
    int nums;
    //if file is not found then exit and give error
    if (!op) {
        perror("Failed to open file!\n");
        exit(1);
    }
    else {
        while (fgets(x, sizeof(x), op)) {
            //pounter to get the first coordinate to W
            char *p = strtok(x, "W");
            //print the first 3 digits of the string
            printf("%.4sd\n", p);
            printf("Next two: %.2s\n", p + 4);
        }
    }
    return 0;
}

旁注:我添加了一个缺失stdio.h的包含。请打开编译器警告,因为此错误会被它们捕获。


推荐阅读