【问题标题】:Operations with text and delimiters带有文本和分隔符的操作
【发布时间】:2016-06-06 13:02:00
【问题描述】:

任务是:从文件中读取文本并从键盘读取分隔符数组。程序应该搜索文本中的分隔符序列,如果找到 3 次或更多,则将所有奇数字符串交换成一个圆圈。它还应该检测用户输入的所有超过长度限制的单词,但仅限于奇数字符串。 这就是我现在得到的:

#include "stdafx.h"
#include <stdio.h>
#include <conio.h>

int main(void)
{
    setlocale(LC_ALL, "Russian"); //entering the text
    const int numberOfCharactersToRead = 128;
    char* inputText = (char*)(malloc(sizeof(char) * numberOfCharactersToRead));
    FILE *fp;
    fopen_s(&fp, "D:\texxxt.txt", "r");
    if (fp == NULL)
    {
        printf("nFile not foundn");
        system("pause");
        return 0;
    }
    fgets(inputText, numberOfCharactersToRead, fp);
    printf("Enter the sequence of delimiters: "); //entering delimiters
    const int numberOfDelimitersToRead = 6;
    char* delimiters = (char*)(malloc(sizeof(char) * numberOfDelimitersToRead));
    int indexer = 0;
    for (indexer = 0; indexer < numberOfDelimitersToRead; indexer++)
    {
        delimiters[indexer] = getchar();
    }
    //Trying to use strtok in order to devide text into rows (unsuccesful)
    char delims[] = "/n";
    char *pch = strtok_s(NULL, inputText, &delims);
    printf("nLexems:");
    while (pch != NULL)
    {
        printf("n%s", pch);
        pch = strtok_s(NULL, inputText, &delims);
    }
    return 0;
}

int symcount(void) 
{ //function searching the quantity of delimiters
    char str[20], ch;
    int count = 0, i;
    printf("nEnter a string : ");
    scanf_s("%s", &str);
    printf("nEnter the character to be searched : ");
    scanf_s("%c", &ch);
    for (i = 0; str[i] != ''; i++) 
    {
        if (str[i] == ch)
            count++;
    }
    if (count == 0)
        printf("nCharacter '%c'is not present", ch);
    else
        printf("nOccurence of character '%c' : %d", ch, count);
    return (0);
}

我真的不知道如何将文本分成行以及如何使我的程序区分偶数和奇数字符串。我真的很困惑

【问题讨论】:

  • 首先正确界定您的代码...

标签: c text


【解决方案1】:

strtok_s的定义如下:

char *strtok_s(char *strToken, const char *strDelimit, char **context);

您正在混淆参数。第一个参数应该是指向输入字符串的指针,第二个参数应该是分隔符字符串。最后,在函数执行后,第三个参数将传递一个指向找到分隔符的位置之后的字符串的指针,如果没有找到分隔符,则为NULL。然后可以将此指针传递给下一个 strtok_s 调用以继续搜索。

char *pchNext;
char *pch = strtok_s(inputText, delimiters, &pchNext);

while (pch != NULL)
{
    printf("\n%s", pch);
    pch = strtok_s(NULL, delimiters, &pchNext); // The first parameter can be NULL here
}

另外,换行符的文本表示是\n,而不是/nn

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 2015-07-07
    • 1970-01-01
    相关资源
    最近更新 更多