the c program1.8

本文提供了一个简单的程序,用于统计输入文本中的空格、制表符和换行符数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编写一个用于统计空格、制表符与换行符个数的程序

#include <iostream>
using namespace std;
int main()
{
	int c;
	int blanks;
	int tabs;
	int newlines;
	blanks=0;
	tabs=0;
	newlines=0;
	while ((c=getchar()) != EOF)
	{
		if (c == ' ') blanks++;
		if (c == '\t')tabs++;
		if (c == '\n')newlines++;
	}
	cout<<blanks<<endl;
	cout<<tabs<<endl;
	cout<<newlines<<endl;
	return 0;
}
//int main()
//{
//  int blanks, tabs, newlines;
//  int c;
//  int done = 0;
//  int lastchar = 0;
// 
//  blanks = 0;
//  tabs = 0;
//  newlines = 0;
// 
//  while(done == 0)
//  {
//    c = getchar();
// 
//    if(c == ' ')
//      ++blanks;
// 
//    if(c == '\t')
//      ++tabs;
// 
//    if(c == '\n')
//      ++newlines;
// 
//    if(c == EOF)
//    {
//      if(lastchar != '\n')
//      {
//        ++newlines; /* this is a bit of a semantic stretch, but it copes
//                     * with implementations where a text file might not
//                     * end with a newline. Thanks to Jim Stad for pointing
//                     * this out.
//                     */
//      }
//      done = 1;
//    }
//    lastchar = c;
//  }
// 
//  printf("Blanks: %d\nTabs: %d\nLines: %d\n", blanks, tabs, newlines);
//  return 0;
//} 


<think>问题:用户提供的代码框架中有一个注释“CouldnotbuildtheprogramfromJARfile.”,这可能是之前尝试构建或运行JAR文件时遇到的问题。不过,用户的主要请求是完成一个Flink程序,该程序从NC(Netcat)接收数据流并实时计算词频。用户已经提供了一个代码框架,我们需要在标记为“Begin”和“End”的注释之间填写代码。根据用户提供的框架,我们需要完成以下任务:1.定义socket的端口号(可能通过参数获取,默认9999)2.获取运行环境(StreamExecutionEnvironment)3.连接socket获取输入数据4.计算数据(将每行分割成单词,然后进行keyBy和窗口计算)5.打印结果到控制台6.调用execute方法启动任务注意:用户已经定义了一个内部类WordWithCount,用于存储单词和计数。我们将在代码中使用5秒的滚动窗口进行词频统计。同时,考虑到用户可能通过命令行参数指定端口,我们使用ParameterTool来解析参数。代码实现如下:</think>我理解您遇到了构建问题,这通常是由于依赖或配置问题导致的。以下是完整的 Flink 程序解决方案,包含详细的构建说明和代码解释: ### 完整解决方案:Flink 实时词频统计程序 ```java import org.apache.flink.api.common.functions.FlatMapFunction; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.windowing.time.Time; import org.apache.flink.util.Collector; public class WordCount { public static void main(String[] args) throws Exception { // 1. 获取参数配置 final ParameterTool params = ParameterTool.fromArgs(args); final int port = params.getInt("port", 9999); // 默认端口9999 // 2. 创建执行环境 final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); // 3. 设置全局配置参数 env.getConfig().setGlobalJobParameters(params); // 4. 连接socket数据源 DataStream<String> text = env.socketTextStream("localhost", port, "\n"); // 5. 数据处理流程 DataStream<WordWithCount> windowCounts = text // 拆分单词 .flatMap(new FlatMapFunction<String, WordWithCount>() { @Override public void flatMap(String value, Collector<WordWithCount> out) { // 转换为小写并分割单词 String[] words = value.toLowerCase().split("\\W+"); for (String word : words) { if (!word.isEmpty()) { out.collect(new WordWithCount(word, 1L)); } } } }) // 按单词分组 .keyBy("word") // 定义5秒滚动窗口 .timeWindow(Time.seconds(5)) // 聚合计数 .reduce((a, b) -> new WordWithCount(a.word, a.count + b.count)); // 6. 输出结果到控制台 windowCounts.print().setParallelism(1); // 7. 执行任务 env.execute("Socket Window WordCount"); } // POJO类:存储单词和计数 public static class WordWithCount { public String word; public long count; public WordWithCount() {} // Flink需要空构造函数 public WordWithCount(String word, long count) { this.word = word; this.count = count; } @Override public String toString() { return word + " : " + count; } } } ``` ### 构建和运行说明(解决 JAR 构建问题) #### 1. Maven 依赖配置(pom.xml) ```xml <project> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>flink-wordcount</artifactId> <version>1.0-SNAPSHOT</version> <properties> <flink.version>1.15.4</flink.version> <java.version>1.8</java.version> </properties> <dependencies> <!-- Flink 核心依赖 --> <dependency> <groupId>org.apache.flink</groupId> <artifactId>flink-streaming-java</artifactId> <version>${flink.version}</version> <scope>provided</scope> </dependency> <!-- Flink 客户端依赖 --> <dependency> <groupId>org.apache.flink</groupId> <artifactId>flink-clients</artifactId> <version>${flink.version}</version> </dependency> </dependencies> <build> <plugins> <!-- 编译插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> <!-- 打包插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.2.4</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <filters> <filter> <artifact>*:*</artifact> <excludes> <exclude>META-INF/*.SF</exclude> <exclude>META-INF/*.DSA</exclude> <exclude>META-INF/*.RSA</exclude> </excludes> </filter> </filters> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> ``` #### 2. 构建 JAR 文件的步骤 ```bash # 1. 创建项目目录结构 mkdir -p src/main/java mv WordCount.java src/main/java/ # 2. 创建 pom.xml (复制上面的内容) nano pom.xml # 3. 使用 Maven 构建 JAR mvn clean package # 构建成功后,JAR 文件位于: # target/flink-wordcount-1.0-SNAPSHOT.jar ``` #### 3. 运行程序 ```bash # 启动 Netcat 服务器 (在另一个终端) nc -lk 9999 # 运行 Flink 程序 flink run -c WordCount target/flink-wordcount-1.0-SNAPSHOT.jar --port 9999 ``` ### 常见构建问题解决方案 1. **ClassNotFoundException 错误** - 原因:缺少 Flink 依赖 - 解决:确保 `pom.xml` 包含正确的依赖,使用 `mvn dependency:tree` 检查 2. **NoSuchMethodError 错误** - 原因:依赖版本冲突 - 解决:添加 `<scope>provided</scope>` 避免打包 Flink 核心库 3. **JAR 文件太大** - 原因:打包了不必要的依赖 - 解决:使用 `maven-shade-plugin` 排除不需要的资源文件 4. **入口类找不到** - 原因:MANIFEST.MF 未正确配置 - 解决:使用 `maven-shade-plugin` 自动处理清单文件 5. **端口占用问题** - 解决:使用不同端口或释放占用端口 ```bash netstat -tuln | grep 9999 kill <PID> ``` ### 程序优化说明 1. **大小写处理**: ```java value.toLowerCase() // 统一转换为小写 ``` 确保 "Hello" 和 "hello" 被视为同一单词 2. **单词分割优化**: ```java split("\\W+") // 匹配非单词字符 ``` 正确处理带标点的单词(如 "world!" → "world") 3. **空字符串过滤**: ```java if (!word.isEmpty()) // 跳过空字符串 ``` 避免无效计数 4. **窗口触发机制**: ```java .timeWindow(Time.seconds(5)) // 5秒滚动窗口 ``` 每5秒输出一次聚合结果
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值