not printing out all alphabet just one letter but it needs to print out every letter after the one that was entered

问题内容:

so far it just prints out z after a but after a is b so i want it to print b c d e f g….z

#include <iostream>

using namespace std;

int main() 
{
   char a = 'a';
   while (a < 'z')
   a++; 
  cout << a; 
}

im just looking for some help on how to do that then after that i need to enter 2 letters and do that with 2 letters but that is just for me i know this is not a code writing service just looking for some help on how to do that. thanks any help is good

问题评论:

答案:

答案1:

Need to put the cout inside the loop:

#include <iostream>

int main() 
{
   char a = 'a';
   while (a < 'z')
   {
      a++; 
      std::cout << a << " "; 
   }
}

Also added a space to distinguish the different letters. And removed the using namespace std; as it’s not recommended.

答案评论:

1  
a std::cout << "\n" at the end would be useful 😉

答案2:

C++ ain’t python: you need to enclose multiple statements in braces:

int main() 
{
    char a = 'a';
    while (a < 'z'){
        a++; 
        cout << a; 
    }
    cout << '\n'; // let's have a line break at the end
}

Otherwise the cout statement is only ran once the loop finishes.

Sadly though this code is not portable since the C++ standard mandates few requirements as to how the alpha characters are encoded. And their being contiguous and consecutive is not a requirement. The portable solution is the obvious if ostensibly puerile

int main()
{
    std::cout << "abcdefghijklmnopqrstuvwxyz\n";
}

Finally, if you want to print all letters from a certain value, then use something like

int main() {
    const char* s = "abcdefghijklmnopqrstuvwxyz";   
    char c = 'k'; // print from just after k onwards, for example
    for (++c/*just after the letter*/; *s /*to prevent overrun*/ && *s != c; ++s);      
    std::cout << s; 
}

答案评论:

1  
Even if it were Python, OP’s code would have made the interpreter complain about bad indentation.

答案3:

Only thing executed in while is a++; because there are no brackets surrounding statements that belongs to while. to do multiple statements surround them in brackets. Or like in this case its possible to make them into one statement.

#include <iostream>

int main() 
{
    char a = 'a';
    while (a < 'z')
        std::cout << ++a;
}

答案评论:

1  
it won’t print ‘a’ 😉
    
@YSC: My edit put the z in danger. This is too difficult for me to fix. I’ve rolled back.
1  
@Bathsheba s/difficult/much work/ ? 😀
    
Indeed! Their question is so difficult to parse in my brain I missed that. (I was answering to deleted comment from Haruki poiting out OP asked not to print the starting letter).
    
@YSC: It’s fortunate then that you can play the portability card and write it out longhand 😉

原文地址:

https://stackoverflow.com/questions/47754693/not-printing-out-all-alphabet-just-one-letter-but-it-needs-to-print-out-every-le

Tags:

Add a Comment