有人可以向我解释为什么这段代码不会执行while条件? 我只是想知道为什么代码会以这种方式运行,或者是否有其他方法可以使它工作。谢谢
UPDATE !!!
嗨顺便说一下这是代码,我对C ++不是很熟悉,所以我不确定程序是否会在开关上跳过while条件。谢谢
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#define MAX 100
using namespace std;
int main()
{
void remove(char[]);
void add(char[], char);
char cstring[MAX];
char letter;
int ecount;
std::string str;
char selection;
cout << "Enter String: ";
cin.getline(cstring, MAX);
cout << "Size of String: " << strlen(cstring) << endl;
bool gameOn = true;
while (gameOn != false){
cout<<"\n Menu";
cout<<"\n========";
cout<<"\n A - Append";
cout<<"\n X - Exit";
cout<<"\n Enter selection: ";
cin>>selection;
switch(selection)
{
case 'A' :
case 'a' :
cout << " Add Element: ";
while (letter!='\n')
{
letter = cin.get();
add(cstring, letter);
}
cout << "\n Output String: " << cstring;
ecount = strlen(cstring) - 1;
cout << " Size of String: " << ecount<< endl;
break;
case 'X' :
case 'x' :{cout<<"\n To exit the menu";}
break;
default : cout<<"\n !!Invalid selection!!"<< endl;
}
}
cout<<"\n";
return 0;
}
char * add( char *cstring, char c )
{
int letter = strlen( cstring );
if ( letter < MAX - 1 )
{
cstring[letter] = c;
cstring[letter + 1] = '\0';
}
return ( cstring );
}
答案 0 :(得分:1)
这是我疯狂的猜测。
我认为你必须初始化letter
。
使用以下代码检查它。
是调试您正在切换的selection
的值。
switch(selection)
{
case 'A' :
case 'a' :
cout << "Add Element: ";
letter = cin.get(); // this will initialize the char letter;
while (letter != '\n') // or use ascii value of new line char in while condition
{
add(cstring, letter); // first add it to string
letter = cin.get(); // then get next letter
}
cout << "String: " << cstring;
ecount = strlen(cstring) - 1; // ecount must be a int
cout << "Size of String: " << ecount<< endl;
break;
希望这会对你有所帮助
答案 1 :(得分:1)
问题出在您正在阅读的输入中,当您在
中阅读字符时cin>>selection;
它将读取一个字符并将其置于选择状态,当您按Enter键时,它将被存储在letter
中,而您的循环将永远不会执行。
请参阅下面的代码,它工作正常;
#include<iostream>
#include <stdio.h>
#include <string.h>
#include<algorithm>
#include<cstring>
#include<vector>
#define MAX 100
using namespace std;
int main()
{
void remove(char[]);
void add(char[], char);
char cstring[MAX];
char letter;
int ecount;
std::string str;
char selection;
cout << "Enter String: ";
cin.getline(cstring, MAX);
cout << "Size of String: " << strlen(cstring) << endl;
bool gameOn = true;
while (gameOn != false){
cout<<"\n Menu";
cout<<"\n========";
cout<<"\n A - Append";
cout<<"\n X - Exit";
cout<<"\n Enter selection: ";
cin>>selection;
cout<<"\n selection="<<selection;
switch(selection)
{
case 'A' :
case 'a' :
selection=cin.get();
cout << " Add Element: ";
while (letter!='\n')
{
letter = cin.get();
add(cstring, letter);
}
cout << "\n Output String: " << cstring;
ecount = strlen(cstring) - 1;
cout << " Size of String: " << ecount<< endl;
break;
case 'X' :
case 'x' :cout<<"\n To exit the menu";
gameOn=false;
break;
default : cout<<"\n !!Invalid selection!!"<< endl;
}
}
cout<<"\n";
return 0;
}