检查c++中字符串中某个字符的值
check the value of a character in a string in c++
我正在写一个程序,读取和写入一个。txt文件与c++。以下是部分编辑过的代码示例:
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>
#include <windows.h>
#include <sstream>
#include <algorithm>
//functions
template <typename T>
string num_to_string(T pNumber)
{
ostringstream oOStrStream;
oOStrStream << pNumber;
return oOStrStream.str();
}
bool isdot(const char &c)
{
return '.'==c;
}
//needed for string_to_num()
float string_to_num(string s)
{
s.erase(remove_if(s.begin(), s.end(), &isdot ),s.end());
replace(s.begin(), s.end(), ',', '.');
stringstream ss(s);
float v = 0;
ss >> v;
return v;
}
//code
string line = 10/20;
//the line taken from the .txt file
float add_numerator = 5;
float add_denominator = 10;
//these are values just for example
for(int i = 0; i < line.size(); i+= 1) {
if (numerator_finished == false){
if (line[i] != "/"){
numerator += line[i];
}else {
numerator_finished = true;
}
}else {
denominator += line[i];
}
}
float numerator_temp = string_to_num(numerator);
float denominator_temp = string_to_num(denominator);
numerator_temp += add_numerator;
denominator_temp += add_denomitator;
numerator = num_to_string(numerator_temp);
denominator = num_to_string(denominator_temp);
string add_string = numerator + "/" + denominator;
//add_string is what the line in the .txt file is changed to with not shown code
如果运行这段代码,它应该是add_string = "15/30"。然而,由于这一行,它将无法编译:
if (line[i] != "/"){
由于这一行出现了这个错误:
"ISO c++禁止指针和整数的比较[-fpermissive]"
我不明白为什么这是一个指针和一个整数,当它们都是字符串。
可以解释这个错误并显示修复方法吗?
我不明白为什么这是一个指针和一个整数,当它们都是字符串。
它们都是而不是字符串!line
是字符串,但line[i]
是char
。
"/"
是一个字符数组(字符串字面值)。
使用'/'
来获得字符字面量,这将与char
进行很好的比较。
相关文章:
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 指向指向字符数组的指针数组的指针
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 比较字符数组
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++中无符号字符溢出
- 使用无符号字符数组有效存储内存