检查c++中字符串中某个字符的值

check the value of a character in a string in c++

本文关键字:字符 c++ 字符串 检查      更新时间:2023-10-16

我正在写一个程序,读取和写入一个。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进行很好的比较。