简体   繁体   中英

The cmd closes without finishing the process in C++

When I run the code below, it takes my input and then the cmd closes without giving any error, the same Logic is used to Java and it worked.

#include <iostream>
using namespace std;

int main(){
string s;
int l = s.length();
int i,flag = 0;
cin >> s;
char c;

for(i = 0; i < l; i++){

    while(i<l && s[i] <= '9' && s[i] >= '0'){
            char c = s[i];
            cout << c;
            i++;
            flag++;
    }
    if( flag > 0){
        flag = 0;
        cout << " ";
    }

}


return 0;

}
  1. Just like nacho searles said, your console is closed because work is done. A cin.get() or other blocking code could keep console not closing.

  2. Since C++ is pass by value by default, your assignment of l doesn't link to s.length() dynamically. Your for loop would run 0 times.

You may assign value to s before getting its length.

string s;
cin >> s;
int l = s.length();
  1. It seems i isn't needed out of for loop, you may define i in for loop like for(int i = 0; i < l; i++) .

Add something like this before you return 0:

cin.get();

The console is getting closed before you are able to read the output.

Welcome to the SO!

It is okay that your program is closing after execution. It is closed because it riched the

return 0;

line. It automatically closes on this line.

Everything you should do to slow down the closing is to wait before

return 0;

You can wait user's input adding line this way:

cin >> s;
return 0;

It is the most common solution in your case.

So I have made some changes and the code worked.. Although the code ran, it still have errors.

cin >> s; was changed to getline (cin, s);

char c = s[i]; and cout << c; was changed to cout << s[i];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM