Screenshot of the outputs i got for the code如何编码以分隔整个部分和十进制部分
我写了这段代码,但有时会给出不同的值。我不知道为什么?
import fileinput
import os
import textwrap
import msvcrt
import sys
text2 = 'Input password :'
def getPASS():
for line in textwrap.wrap(text2, width=50):
print(line.ljust(80))
list1 = []
while True:
char = msvcrt.getch()
char =str(char)
char = char[2:-1]
if char == "\\n'" or char == "\\r":
break
elif char == "\\x08":
del list1[-1]
os.system("cls")
print("Input password:")
sys.stdout.write("*" * len(list1))
sys.stdout.flush()
continue
else:
list1.append(char)
sys.stdout.write("*")
sys.stdout.flush()
return "".join(list1)
psw = getPASS()
while True:
invalid = ' ,:;/?"\}]{[-=+!@#$%^&*()|'
for x in psw:
if x in invalid:
print("Character %r is not allowed in password" % x)
break # from for x in psw
else:
break # from while True
newpassword = psw
script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, 'alert' , 'temp' , 'temp folder' , 'temp' , 'myapp.py')
print(file_path)
NameFile = file_path
with fileinput.FileInput(NameFile, inplace=True, backup='.bak') as file:
for line in file:
print(line.replace(password, newpassword), end='')
输入浮点值
22.47
22之前46之后
用户@用户:〜/ cpp $ ./a.out
输入浮点值
2234.127
2234之前126之后
用户@用户:〜/ cpp $ ./a.out
输入浮点值
22.335
之前22之后334
用户@用户:〜/ cpp $ ./a.out
输入浮点值
222.88
222之前88之后
这些是我尝试过的一些值。
答案 0 :(得分:0)
如何编码以将整个部分和小数部分分开?
我假设您想仅将表示的浮动值分为非小数部分和小数部分。在这种情况下,将用户输入作为std::string
,然后执行以下操作。我希望这些注释能使您理解代码:
#include <iostream>
#include <string>
#include <cstddef> // std::size_t
int main()
{
std::cout << "enter the float value\n";
std::string strInput; std::cin >> strInput; // take the user input as std::string
std::size_t pos{ 0 };
// find the position of charector decimal point('.') using std::string::find
pos = strInput.find(".", pos);
// if the decimal point is found in the user input: x = substring starting from 0 to pos of user input.
const std::string x = pos != std::string::npos ? strInput.substr(0, pos) : strInput;
// if the decimal point is found in the user input: y = substring starting from pos + 1 to end of user input.
const std::string y = pos != std::string::npos ? strInput.substr(pos + 1) : std::string{ "" };
std::cout << "before " << x << " after " << y << '\n';
return 0;
}
示例输入:
enter the float value
0123.04560
输出:
before 0123 after 04560
PS :但是,就像上面给出的示例一样,在分隔的小数部分(0123
和04560
之前都为零可能是不需要的。在这种情况下,请使用 any of the standard functions 将其转换回整数,或者使用 erase-remove idiom 从头开始删除零。