首页 > 解决方案 > 当我重复该程序时,它会跳过数组条目

问题描述

该程序的主要任务是使用带有 2 个用户选择的字母的 char 数组查找单词。这完成了任务,但我还需要能够重复该程序,当我这样做时跳过数组条目,我尝试使用 fflush( NULL) 在将 getline() 更改为 scanf() 后,我也尝试过 fflush(stdin),但如果 IDE 更改了我正在使用 Visual Studio 2019 的任何内容,它们都不起作用。

#include <iostream>
#include <cmath>
#include <stdio.h>
#include <conio.h>

using namespace std;


int arrLength(char mas[]);

void upperCaseArr(char mas[]);

void returnWords(char mas[], char x);


int main()
{
    int rep = 1;

    while (rep == 1) {        
        system("cls");
        char mas[256], x, b;   
        int i = 0;

        cout << "write a sentence!\n\n";

        fflush(NULL);
        cin.getline(mas, 256);     
        upperCaseArr(mas);

        cout << "\n\n\n";

        cout << "enter a letter! if two of these letters will be in a word then it'll be written out.\n";
        cin >> x;
        x -= 32;                          
        cout << "\n\n\n";

        cout << "words that have 2 your letters:\n";
        returnWords( mas , x);    

        cout << "\n\n\nDo you want to repeat? (Y/N)\n";

        int x1 = 0;
        while (x1 == 0) {           

            cin >> b;

            if (b == 'Y' || b == 'y') {
                rep = 1;
                x1 = 1;
            }
            else if (b == 'N' || b == 'n') {
                rep = 0;
                x1 = 1;
            }
            else {
                cout << "Invalid operator!" << endl;
            }
        }

    }
}

int arrLength(char mas[]) {                  
    int x = 0;                             
    for (int i = 0; i <= 256; i++) {
        if (mas[i] == '\0') { break; }
        else { x++; }
    }
    return x;
}

void upperCaseArr(char mas[]) {             
    int length = arrLength(mas);
    for (int i = 0; i < length; i++) {
        int c = mas[i];
        if (islower(c)) {
            mas[i] = toupper(c);
        }
    }
};

void returnWords(char mas[], char x) {
    int length = arrLength(mas), ssiz = 0, sp = 0; 
    int space[100];

    for (int i = 0; i <= length; i++) {  
        char m = mas[i];
        if (m == ' ') { space[sp] = i + 1; sp++; }
    };

    for (int i = sp; i < 100; i++) { space[i] = -1; }  /
    for (int i = 0; i < 100; i++) { if (space[i] != -1) { ssiz++; } }
    if (ssiz == 0) { ssiz = 1; space[sp] = length; }                 
    if (mas[length] != ' ') { ssiz += 1; space[sp] = length + 1;}      
    for (int i = 0; i < ssiz; i++) {           
        int sk = 0;
        int i1 = 0, i2 = 0;

        if (i > 0) { i1 = space[i] - (space[i] - space[i - 1]); }  

        for (i1; i1 < space[i]; i1++) {     
            char m = mas[i1];
            if (x == m) { sk++; };
        }

        if (i > 0) { i2 = space[i] - (space[i] - space[i - 1]); } 

        if (sk == 2) {
            for (i2; i2 < space[i]; i2++) {        
                cout << mas[i2];
            }
        }
    }
};

标签: c++arrayscharbuffer

解决方案


推荐阅读