[英]How to get multiple input with char and multiple output with int? C++
我對C ++很陌生,所以如果我聽起來沒技術,我會道歉。 我在使用我的代碼獲取多個輸入和輸出時遇到一些麻煩,我想我應該有一個循環來獲取數據,但我不知道我的代碼中是如何進行的,我認為關於使用getline(),但似乎不想使用Char。
我已經嘗試了getline,但我不確定如何用Char輸入實現它,我相信我可能還需要一個單獨的循環,但同樣不太確定。 我認為它也可以用於EoF。
這是我的代碼:
int main()
{
char inpval;
int outval = 0;
cout << "Enter a Roman Number to convert: " << endl;
while (cin.get(inpval))
{
inpval = toupper(inpval);
if (inpval == 'M')
outval = outval + 1000;
else if (inpval == 'D') {
inpval = cin.peek();
inpval = toupper(inpval);
if (inpval == 'M') {
outval = outval - 500;
continue;
} else {
outval = outval + 500;
continue;
}
}
//etc
cout << "The Equivalent Arabic value is:" << endl;
cout << outval << "\n";
return 0;
}
我的預期輸出是:
(全部換行)輸入:I II IV V VI
輸出:1 2 4 5 6
實際輸出是:
輸入:我
輸出:1
PS:該程序將Roman Numeral字符轉換為他們尊重的數字。
任何幫助表示贊賞!
您可以使用以下語法從cin中輸入多個項目。
cin >> a;
cin >> b;
cin >> c;
另一種方式也在那里
cin >> a >> b >> c;
這種技術稱為“操作員鏈接”,與上述類似。
方法1:使用getchar()
,計算/轉換羅馬為整數,直到遇到空格'',當你得到一個空格' '
輸出整數並執行相同的下一個羅馬數字,直到你得到另一個空格' '
或換行'\\n'
並在遇到換行符'\\n'
停止程序。
方法2:使用類型std::string
並使用getline
獲取輸入。 然后遍歷字符串並進行計算,直到找到空格' '
輸出數字,執行相同操作直到找到下一個空格' '
或在字符串結束時結束。
如果您知道要轉換的羅馬數字的數量,則可以將其置於循環中。 希望這可以幫助。
示例(方法2)
#include <bits/stdc++.h>
int value(char r)
{
if (r == 'I')
return 1;
if (r == 'V')
return 5;
if (r == 'X')
return 10;
if (r == 'L')
return 50;
if (r == 'C')
return 100;
if (r == 'D')
return 500;
if (r == 'M')
return 1000;
return -1;
}
int main()
{
int out=0;
std::string s;
std::string::iterator i; //string iterator
//for more info go to https://www.geeksforgeeks.org/stdstring-class-in-c/
getline(std::cin,s);
for (i = s.begin(); i!= s.end() ; ++i)
{
if(*i != ' ')//Encounter a space, output result and
{ //go to next roman numeral
int s1 = value(*i);
if (*(i+1) != ' ' || *(i+1) != '\0')
{
// Getting value of i+1 nth Element
int s2 = value(*(i+1));
// Comparing both values
if (s1 >= s2)
{
// Value of current symbol is greater
// or equal to the next symbol
out = out + s1;
}
else
{
out = out + s2 - s1;
i++; // Value of current symbol is
// less than the next symbol
}
}
else
{
out = out + s1;
i++;
}
}
else
{
std::cout<<out<<" ";
out = 0;
}
}
std::cout<<out<<" ";
std::cout<<std::endl;
return 0;
}
輸入:
I II MM MCMIV
輸出:
1 2 2000 1904
你這樣做有什么問題嗎?
cout << "Enter a Roman Numeral" << endl;
string inpval;
cin >> inpval;
while (inpval != "exit")
{
int outval = 0;
if (inpval == "I")
outval = 1;
else if (inpval == "II")
outval = 2;
else if (inpval == "III")
outval = 3;
else if (inpval == "IV")
outval = 4;
// ect
cout << "The Equivalent Arabic value is: " << outval << endl << endl;
cout << "Enter next numeral: (type exit to exit) " << endl;
cin >> inpval;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.