Domanda

This is the snippet of code that I'm puzzled about.
I'm checking for how long an incoming string is.
I've appended * in order to have a sentinel value to stop the while loop.
Yet, I'm consistently getting a length value that is inclusive of the * and I don't understand why, since the while loop with the nested if ought to stop prior to the *.

Can someone point out what I'm doing wrong and why I'm having this issue?

void conversion(string romanIn)
{
    length=0;
    romanIn.append("*");

    while(item!="*")
    {

        if(item != "*")
        {
        item = romanIn[length];
        length++;
        }
        cout<<item;
    }
È stato utile?

Soluzione

you are naturally going to get a +1 the first time through the loop because you aren't initializing the variable "item". Also make it a do while instead of a while loop.

Try this:

do
{

    // This line moves out of the if statement
    item = romanIn[length];

    if(item != "*")
    {
        length++;
    }
    cout<<item;
}while(item!="*")

Altri suggerimenti

What is the initial value of item?

Let's assume it's 0. You enter the loop item == 0 != marker, so you enter the if as well, and you say

item = romanIn[0], length++

If romanIn[0] == "*" you will exit the loop, but your length now says 1 which includes the marker

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top