Citat:
Ursprungligen postat av
bosscs2
äsch struntsamma jag provar låta programmet ta input med return.
Däremot undrar jag hur man stoppar en while loop med return knappen?
cin >> i;
while(i != return-knappen){
}
Om du istället använder
std::getline stoppar den som default input vid newline och tar bort newline från strängen.
Alltså är längden på retursträngen lika med noll om du enbart trycker på enter.
Därför kan du upprepa loopen om längden är mer än noll.
Om det är heltal som du vill komma åt kan du använda
stoi() på strängen.
http://cpp.sh/3cpmo
Kod:
// Example program
#include <iostream>
#include <string>
int main()
{
std::string name;
std::size_t l;
do
{
std::cout << "What is your name? ";
std::getline (std::cin, name);
l=name.length();
if (l>0)
std::cout << "Hello, " << name << "!\n";
} while (l>0);
}
Läs mer:
Citat:
std::getline (string)
C++98C++11
(1)
istream& getline (istream& is, string& str, char delim);
(2)
istream& getline (istream& is, string& str);
Get line from stream into string
Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n', for (2)).
The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.
If the delimiter is found, it is extracted and discarded (i.e. it is not stored and the next input operation will begin after it).
Note that any content in str before the call is replaced by the newly extracted sequence.
https://www.cplusplus.com/reference/...tring/getline/