Grr*_*Grr 3 c++ tostring c++11
我在尝试将数字转换为字符串时遇到问题.目的是进行错误检查以确保数字具有特定长度.我尝试过使用to_string()和convert.str()函数,但在尝试编译时会收到相同的错误.
我正在使用MinGw g ++进行编译和实现我需要告诉它我想要C++ 11标准,我相信我已经完成了.我的编译器代码如下:
NPP_SAVE
CD $(CURRENT_DIRECTORY)
C:\MinGW\bin\g++ -std=c++11 "$(FULL_CURRENT_PATH)" -o "$(NAME_PART).exe"
cmd /c $(NAME_PART).exe
Run Code Online (Sandbox Code Playgroud)
现在假设这是正确的,我的使用代码to_string()如下:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
int book_code = 0;
cout << "Please enter the four digit book code: ";
cin >> book_code;
string code = to_string(book_code);
while (!(cin >> book_code) || code.length() != 4){
cin.clear();
cin.ignore(10000, '\n');
cout << "That is not a valid code." << endl;
cout << "Please enter the four digit book code: ";
}
}
Run Code Online (Sandbox Code Playgroud)
我使用convert.str()的代码如下:
int main() {
int book_code = 0;
cout << "Please enter the four digit book code: ";
cin >> book_code;
ostringstream Convert;
convert << book_code;
string code = convert.str();
while (!(cin >> book_code) || code.length() != 4){
cin.clear();
cin.ignore(10000, '\n');
cout << "That is not a valid code." << endl;
cout << "Please enter the four digit book code: ";
}
}
Run Code Online (Sandbox Code Playgroud)
这些都没有成功,都返回了
错误:未在此范围内声明'to_string'
我错过了一些明显的东西吗
Jea*_*dey 10
在MinGW std::to_string()不存在的情况下,您应该声明自己的实现.
std::string to_string(int i)
{
std::stringstream ss;
ss << i;
return ss.str();
}
Run Code Online (Sandbox Code Playgroud)
我建议你使用MSYS2,它更加实现,你可以避免这种类型的问题.
编辑:
检查点位置double:
#include <iostream>
#include <sstream>
#include <string>
std::string to_str_with_dot_pos(double i, unsigned int &pos)
{
std::stringstream ss;
ss << i;
std::string result(ss.str());
pos = 0;
while (pos < result.length() && result[pos] != '.') {
pos += 1;
}
return result;
}
int main(int argc, char **argv)
{
double d(12.54);
unsigned int pos(0);
// str should be "12.54".
// pos should be 2.
std::string str = to_str_with_dot_pos(d, pos);
std::cout << "double as string: " << str << std::endl;
std::cout << "double dot position: " << pos << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
代码解释(while循环):
它获取的每个字符std::string并检查它是否与.点字符不相等,如果字符不等于.它将向pos变量添加+1 .
它返回2而不是3,因为我们从0开始计数,而不是1.
此外,这个问题是重复的.
| 归档时间: |
|
| 查看次数: |
14609 次 |
| 最近记录: |