首页 > 解决方案 > 如何修复来自 IF/ELSE 语句的重复 cout 的输出

问题描述

我有一个完整的课程代码;它根据用户要求的字符数创建一个随机字符串,然后允许用户指定是否要在字符串中查找特定的字符对。最后一部分基于if/else语句,它要么给出位置,要么告诉他们字符串中没有对。

我的问题是,当给定一对查找时,如果它在字符串中它给出了更正的语句,但是,它也给出了else重复多次的语句。如果该对不在字符串中,则它会给出正确的else语句,但会重复cout几次。我不知道如何解决这个问题。

这是我的代码和输出的屏幕截图。

图片

图片

#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

int main() {

    int i=0, n;
    char alphabet[26];
    char RandomStringArray [100];
    char Ltr1, Ltr2;
    srand(time(0));

    cout <<"How many letters do you want in your random string (no less than 0, no more than 100): ";
    cin >> n;

    for (int i=0; i<=25; i++)
            alphabet[i] = 'a' + i;

    while(i<n) {
        int temp = rand() % 26;
        RandomStringArray[i] = alphabet[temp];
        i++;
    }

    for(i=0; i<n; i++)
        cout<<RandomStringArray[i];
    cout<<"\n";

    cout<<"What letter pair would you like to find? ";
    cin>>Ltr1>>Ltr2;

    for (i=0; i<n; i++)
        if (Ltr1==RandomStringArray[i] && Ltr2== RandomStringArray[i+1]){
            cout<<"The pair is in the string starting at character number "<<i+1<<" in the string. \n";
        }
        else if (Ltr1!=RandomStringArray[i] && Ltr2!= RandomStringArray[i+1])
            cout<<"no";

    return 0;
}

标签: c++

解决方案


由于您已将if...else构造放置在for循环内,因此每次都会对其进行评估。这意味着对于第一个条件不成立的每个实例,else都会执行该子句,从而导致您的“否”消息重复。


推荐阅读